Codiqo

Learn C# · lesson 4 of 61 · about 7 minutes

Arithmetic

Work out damage and loot with + - * / %, and use integer division for half damage, rounded down.

What you'll learn

  • Use the arithmetic operators
  • Predict integer division
  • Know when + adds and when it joins

Damage maths

Battles are full of sums: damage, healing, experience points. C# has + - * / %.

When both sides of / are ints, the decimals are dropped: 7 / 2 is 3. Games use this on purpose: half damage, rounded down. With a double involved you get the decimals: 7 / 2.0 is 3.5. % gives the remainder: 7 % 2 is 1.

Splitting the XP

int xp = 25;
int party = 2;
Console.WriteLine("Each gets " + xp / party + " XP");
Console.WriteLine("Left over: " + xp % party);
Console.WriteLine("Exactly: " + xp / 2.0);

Output

Each gets 12 XP
Left over: 1
Exactly: 12.5

+ does two jobs

With two numbers, + adds. With text on either side, it joins. C# works from left to right, so "Total: " + 2 + 3 is Total: 23: the text is joined with 2 first, then with 3.

Put a sum in brackets to work it out first. *, / and % already happen before +, so they need no brackets.

Brackets decide

Console.WriteLine("Total: " + 2 + 3);
Console.WriteLine("Total: " + (2 + 3));

Output

Total: 23
Total: 5

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.