Determine Odd or Even

πŸ“– Instructions#

With the sum calculated, we now need to check whether it is odd or even. The result of that check is not a number β€” it’s a boolean: either true or false.

We can get that result by combining the modulo operator with a comparison β€” a pattern explained in the arithmetic operators vault page.

🧠 Recall

βœ… What to Do#

Declare a boolean variable named sumIsEven and assign it the result of checking whether sum is even using modulo and a comparison.

🎯 Expected Outcome#

No visible change in the console output. The result is stored in sumIsEven and will be used in the next lesson to decide the winner.

πŸ’‘ Hints#

Hint 1

A number is even if its remainder after division by 2 is 0.

Hint 2

You need two operators on the right side: one arithmetic and one comparison.

Hint 3

The variable type is bool. The expression checks the modulo of sum against 0.

⚠️ Common Mistakes#

Storing the modulo result instead of the comparison result

Writing int sumIsEven = sum % 2 stores 0 or 1 instead of true or false. You need the full expression sum % 2 == 0 to get a boolean.

Using the wrong variable type

Declaring int sumIsEven = sum % 2 == 0 causes a compile error β€” a comparison result is a bool, not an int. The variable must be declared as bool.

Confusing = and ==

sum % 2 = 0 attempts to assign 0 to the result of sum % 2, which is not a valid assignment target and causes a compile error. Use == to compare.

Checking against 1 instead of 0

sum % 2 == 1 checks for odd, not even. Since sumIsEven should be true for even numbers, compare against 0.

πŸ™ˆ Solution#

Tried, you must, before reveal the solution you may.

Program.csChanges

  // Check if the sum is odd or even.
+ bool sumIsEven = sum % 2 == 0;

Program.csFinal

Console.WriteLine("Welcome to Odds and Evens!");

// Player chooses to play with odds or evens.
Console.WriteLine("Choose 1 for Odds or 2 for Evens:");
string input = Console.ReadLine();
int playerChoice = int.Parse(input);

if (playerChoice == 1)
{
    Console.WriteLine("You chose Odds.");
}
else
{
    Console.WriteLine("You chose Evens.");
}

// Player enters a number between 1 and 2.
Console.WriteLine("Choose a number between 1 and 2:");
string rawNumber = Console.ReadLine();
int playerNumber = int.Parse(rawNumber);
Console.WriteLine($"You chose: {playerNumber}");

// Computer randomly generates a number between 1 and 2.
Random random = new Random();
int computerNumber = random.Next(1, 3);
Console.WriteLine($"Computer chose: {computerNumber}");

// Add the two numbers.
int sum = playerNumber + computerNumber;
Console.WriteLine($"Sum is: {sum}");

// Check if the sum is odd or even.
bool sumIsEven = sum % 2 == 0;

(...)