Logical operators
Learn boolean logic and short-circuit evaluation with &&, || and !.
Assignment operators
= is the most basic assignment operator: it puts the value on its right into the variable on its left. When you write int score = 10;, the variable score becomes 10.
For shorter code there are compound assignment operators: +=, -=, *=, /=. score += 5 actually means score = score + 5. It takes the old value, does the operation, and stores the result back in the same variable.
%= and chained assignment
The %= operator updates with the remainder. Writing minutes %= 60 stores the remainder of minutes divided by 60 back into minutes; this keeps the value from exceeding 60.
Multiple compound assignments can be chained: cart += item1; cart += item2;. Each addition runs in order. The code reads more cleanly and repeats itself less.
Exercise Add an item to the cart
Add itemPrice to cart with the += operator. Then print cart with Console.WriteLine. You must use the += compound assignment.
Show example solution
To add to the cart, write cart += itemPrice; and print it with Console.WriteLine.
Example solution:
using System;
class Program
{
static void Main()
{
int cart = 200;
int itemPrice = 50;
// Add to cart and print
cart += itemPrice;
Console.WriteLine(cart);
}
}
Test yourself
-
Write the compound assignment operator
int score = 10; score ____ 5; Console.WriteLine(score);Show answer
int score = 10; score += 5; Console.WriteLine(score); -
int score = 10; score += 5; Console.WriteLine(score); what is the output?
int score = 10; score += 5; Console.WriteLine(score);- 15
- 5
- 10
- 50
Show answer
15 — Correct. 10 + 5 = 15.
-
Match each operator to its meaning
- =
- Assign
- +=
- Add and assign
- -=
- Subtract and assign
- *=
- Multiply and assign