Arithmetic operators
Learn basic arithmetic with +, -, *, / and %.
Arithmetic operators
In C#, the basic four operations on numbers use arithmetic operators: + for addition, - for subtraction, * for multiplication, / for division. These signs keep the meaning they have in everyday math.
For example, to compute a cafe's daily revenue you would write int revenue = price * cups;. The operator takes two values, produces a new one and assigns it to the variable. Precedence matches school math: multiplication and division first, then addition and subtraction.
Modulo, increment and decrement
Two more operators will come in handy. % (modulo) gives the remainder of a division: 17 % 5 returns 2 because 17 = 3*5 + 2. It is great for even or odd checks.
++ increases a variable by one, -- decreases it by one. count++ is the same as count = count + 1. This shortcut is a lifesaver when you keep a counter.
Exercise Compute the total price
Declare a total variable and assign the product of price and quantity. Then print total with Console.WriteLine. Use the * multiplication operator.
Show example solution
To find the total, write int total = price * quantity; and print it with Console.WriteLine.
Example solution:
using System;
class Program
{
static void Main()
{
int price = 25;
int quantity = 4;
// Total price
int total = price * quantity;
Console.WriteLine(total);
}
}
Test yourself
-
What is the output of Console.WriteLine(6 * 7);?
Console.WriteLine(6 * 7);- 36
- 42
- 13
- 67
Show answer
42 — Correct. 6 times 7 is 42.
-
Write the remainder operator
int remainder = 17 ____ 5; Console.WriteLine(remainder);Show answer
int remainder = 17 % 5; Console.WriteLine(remainder); -
Match each operator to its meaning
- +
- Addition
- -
- Subtraction
- *
- Multiplication
- /
- Division