Arithmetic and Expressions in C#
Calculate in C# with + - * / and %, know why 5 / 4 is 1, and work out an expression in the order C# does.
Novice · C# · Updated
After this lesson you can
- Calculate with C#'s arithmetic operators, including integer division and %
- Work out the value of an expression using the order of operations
Key takeaways
- Dividing two
ints keeps only the whole part:5 / 4is 1. Make one of them adoubleto keep the decimals. %gives the remainder: what's left over after dividing.++,--,+=and the other shortcuts change a variable using its own value.- C# works out parentheses first, then
*,/and%, then+and-, each from left to right.
All programming languages can do arithmetic, and most programs do a lot of it: totals, averages, prices, scores. In C# you calculate with operators, symbols like + and *, and combine them into expressions.
The arithmetic operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ |
Addition | 5 + 4 |
9 |
- |
Subtraction | 5 - 4 |
1 |
* |
Multiplication | 5 * 4 |
20 |
/ |
Division | 20 / 4 |
5 |
% |
Remainder | 6 % 4 |
2 |
int shotsMade = 5;
int shotsMissed = 3;
int totalShots = shotsMade + shotsMissed;
Console.WriteLine("Total shots: " + totalShots);
Console.WriteLine("Made minus missed: " + (shotsMade - shotsMissed));
Total shots: 8
Made minus missed: 2
The parentheses around shotsMade - shotsMissed make C# subtract first, then join the answer to the text. Without them, C# would join 5 to the text first, and then complain that it can't subtract from text.
Dividing whole numbers
When both numbers are whole numbers (int), division gives a whole number too. C# keeps the whole part and throws the rest away. It doesn't round:
Console.WriteLine(20 / 4);
Console.WriteLine(5 / 4);
Console.WriteLine(7 / 2);
5
1
3
5 / 4 is 1.25, but an int can't hold the .25, so the answer is 1. The remainder operator % gives you what was left over:
int cookies = 36;
int students = 14;
int cookiesEach = cookies / students;
int cookiesLeftOver = cookies % students;
Console.WriteLine("Each student gets " + cookiesEach + " cookies");
Console.WriteLine("Cookies left over: " + cookiesLeftOver);
Each student gets 2 cookies
Cookies left over: 8
When you want the decimal answer, make at least one number a double or a decimal:
Console.WriteLine(5 / 4.0);
Console.WriteLine(5.0m / 4);
1.25
1.25
Adding one, and other shortcuts
Adding 1 to a variable is so common that C# has a shortcut, the increment operator ++. -- takes 1 away:
int score = 10;
score++; // the same as score = score + 1;
Console.WriteLine(score);
score--; // the same as score = score - 1;
Console.WriteLine(score);
score += 5; // the same as score = score + 5;
Console.WriteLine(score);
score *= 2; // the same as score = score * 2;
Console.WriteLine(score);
11
10
15
30
+=, -=, *= and /= change a variable using its own value. You will see them everywhere.
Expressions and the order of operations
An expression is anything that works out to a value: 3 * 2, or a whole line of arithmetic. A computer works out a long expression one small step at a time, each step one operator and the two values beside it. It follows the order you learned in math class:
- parentheses first
- then
*,/and%, from left to right - then
+and-, from left to right
Here is how to work out 12 + 3 * 2 - 14 / 2 + 10 + 53 step by step, using the order of operations:
12 + 3 * 2 - 14 / 2 + 10 + 53
12 + 6 - 14 / 2 + 10 + 53 3 * 2 is 6
12 + 6 - 7 + 10 + 53 14 / 2 is 7
18 - 7 + 10 + 53 then + and - from the left
11 + 10 + 53
21 + 53
74
Check it:
int answer = 12 + 3 * 2 - 14 / 2 + 10 + 53;
Console.WriteLine(answer);
74
Parentheses change the order, so use them whenever you want something worked out first, or just to make your meaning clear:
Console.WriteLine(2 + 3 * 4);
Console.WriteLine((2 + 3) * 4);
14
20
The Math class
For anything beyond the basic operators, C# has the Math class:
Console.WriteLine(Math.Round(18.4567, 2)); // round to 2 decimal places
Console.WriteLine(Math.Ceiling(3.2)); // round up to a whole number
Console.WriteLine(Math.Max(12, 31)); // the bigger of two numbers
Console.WriteLine(Math.Pow(2, 10)); // 2 to the power of 10
Console.WriteLine(Math.Sqrt(81)); // square root
18.46
4
31
1024
9
Math.Ceiling is handy when a part has to be bought whole: if 42 cookies are needed and they come by the dozen, Math.Ceiling(42 / 12.0) says to buy 4 dozen.
Clear code beats short code
You can put a whole calculation on one line:
// Bill scored 15 points from 3-point shots and 8 points from 2-point shots.
// How many shots did Bill make?
int totalShots = 15 / 3 + 8 / 2;
Console.WriteLine(totalShots);
9
It works, but a reader has to guess what 15, 3, 8 and 2 mean. Numbers like that, dropped into code without a name, are called magic numbers. Give each one a name with a variable, and the code explains itself:
int pointsFromThreePointers = 15;
int pointsFromTwoPointers = 8;
int threePointShots = pointsFromThreePointers / 3;
int twoPointShots = pointsFromTwoPointers / 2;
int totalShots = threePointShots + twoPointShots;
Console.WriteLine("Three-point shots: " + threePointShots);
Console.WriteLine("Two-point shots: " + twoPointShots);
Console.WriteLine("Total shots made: " + totalShots);
Three-point shots: 5
Two-point shots: 4
Total shots made: 9
More lines, but anyone can read it, check it and change it. Fewer lines is not the goal; clear intent is.
Check yourself
2 questions to try on the lesson page.
So what
You can now calculate anything a program needs: whole-number division and remainders for sharing things out, decimals for money, the order of operations for long expressions, and named variables so every calculation explains itself.