c# · level 1 · unit 3 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
C# is a calculator that never gets tired.
Each does one job: + adds, - takes away, * multiplies and / divides. Brackets go first, then * and /, then + and -, as in maths lessons.
Watch out with /. When both numbers are int, C# gives a whole number and drops the rest, so 7 / 2 is 3. Make one of them a double, like 7.0 / 2, to get 3.5.
% gives the , what is left over after sharing out. Share 7 sweets between 2 friends: each gets 3, and 7 % 2 is the 1 sweet left over.
using System;
Console.WriteLine(2 + 3 * 4);
Console.WriteLine((2 + 3) * 4);
Console.WriteLine(7 / 2);
Console.WriteLine(7.0 / 2);
Console.WriteLine(7 % 2); C# never rounds up when it drops the rest, so 9 / 10 is 0.
guess first
Ten sweets, four friends. How many each?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
int sweets = 10;
int friends = 4;
Console.WriteLine(sweets / friends);
your turn
Your turn. Share out a pizza.
Choose how many slices there are and how many friends are sharing. Use whole numbers, and at least 1 friend. Then press run.
output
press run to see what happens
fix it
Two friends share the snacks, but the maths is off. Fix it!
output
press run to see what happens
- 8 plus 6 is 14 snacks, shared by 2, so each friend should get 7. What does C# work out first on line 5?
/goes before+, so only the crisps get shared. Make the adding happen first.- Put brackets round
cookies + crispson line 5, then press run.
nailed it
your code can do maths now. :D
+ - * /work as in maths lessons, brackets first.- Two
intvalues divide into a whole number. %gives the remainder, what is left over.
new words in your collection
- operator
- remainder
This lesson isn’t saved. A free account remembers every lesson you finish.