π Instructions#
With both numbers chosen, we can now add them together. The sum is what we’ll use to determine whether the round is odd or even.
Arithmetic works the same way with variables as it does with plain numbers β you use the variable names in place of the values.
π§ Recall
Here’s what addition looks like with variables:
int a = 3;
int b = 4;
int result = a + b;result holds 7. The program reads the values stored in a and b and adds them together.
π Learn More
β What to Do#
Add playerNumber and computerNumber together, store the result in an integer variable named sum, and print Sum is: followed by its value.
π― Expected Outcome#
Welcome to Odds and Evens!
Choose 1 for Odds or 2 for Evens:
1
You chose Odds.
Choose a number between 1 and 2:
1
You chose: 1
Computer chose: 2
Sum is: 3
π‘ Hints#
Hint 1
The sum goes on the right side of the assignment. The variable that holds it goes on the left.
Hint 2
You already have both numbers stored in variables. Use them directly in the expression.
Hint 3
Printing the sum follows the same pattern as printing the player and computer numbers in the previous lessons.
β οΈ Common Mistakes#
Using the raw input string instead of the parsed integer
rawNumber + computerNumber won’t add the numbers β it will concatenate them as text and produce "12" instead of 3. Always use the parsed integer variables playerNumber and computerNumber.
Printing without storing first
Calculating the sum directly inside the print statement works but makes the value unavailable for the next steps. Store it in sum first, then print it.
Wrong variable name
The variable must be named sum β it’s referenced by name in the lessons that follow.
π Solution#
Tried, you must, before reveal the solution you may.
Program.csChanges
// Add the two numbers.
+ int sum = playerNumber + computerNumber;
+ Console.WriteLine($"Sum is: {sum}");
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}");
(...)