Codiqo

Learn C# · lesson 19 of 61 · about 8 minutes

for Loops

Land a combo attack, one hit for every 10 HP the hero has left: count with a for loop and put loops inside loops.

What you'll learn

  • Read the three parts of a for loop
  • Count up, down and in steps
  • Nest loops for grids

A combo attack

After the wave, the hero strikes back with a combo: one hit for every 10 HP they have left, and each hit does 3 more damage than the one before. With 22 HP that's 2 hits, for 3 and then 6 damage. A loop that counts the hits, one lap each, is what a for loop is for.

Counting loops

for (int i = 0; i < 5; i++) has a start, a condition and a step. The loop variable only exists inside the loop. Put one loop inside another to work through rows and columns.

Counting and a grid

for (int i = 10; i >= 0; i -= 5)
{
    Console.Write($"{i} ");
}
Console.WriteLine();

for (int row = 1; row <= 3; row++)
{
    for (int col = 1; col <= 3; col++)
    {
        Console.Write($"{row * col,3}");
    }
    Console.WriteLine();
}

Output

10 5 0
  1  2  3
  2  4  6
  3  6  9

The combo for a hero with 31 HP

int heroHp = 31;
int hits = heroHp / 10;
int comboTotal = 0;
for (int i = 1; i <= hits; i++)
{
    int dmg = i * 3;
    comboTotal += dmg;
    Console.WriteLine($"Combo hit {i}: {dmg} damage");
}
Console.WriteLine($"Combo total: {comboTotal}");

Output

Combo hit 1: 3 damage
Combo hit 2: 6 damage
Combo hit 3: 9 damage
Combo total: 18

Tip

heroHp / 10 is integer division, so 31 / 10 is 3: three hits, and the last 1 HP doesn't earn a fourth. A hero with under 10 HP gets 0 hits, and a for loop whose condition is false from the start never runs.

Now try it yourself

This lesson is free in Codiqo, with 10 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.