Skip to content
dreamcode
dreamcode
Map
Loops
Lesson 5 of 21
+15 XP on finish
C# LOOPS & ARRAYSChapter 2 · C# Loops & Arrays

Repeating with loops

C# offers several ways to repeat code: for loops (best when you know the count), while loops (runs while a condition is true), and do-while loops (always runs at least once).

Worked example
for (int i = 0; i < 3; i++) {
    Console.WriteLine("Hop: " + i);
}

int count = 0;
while (count < 2) {
    Console.WriteLine("Count: " + count);
    count++;
}

How it reads

  • int i = 0 declares and initializes a counter variable
  • i < 3 tests if the counter is still less than 3
  • i++ increments the counter at the end of each iteration
Cloud tip: Always ensure a while loop has a path to false, otherwise it becomes an infinite loop and hangs the program.

Check your understanding

0 / 2

Answer all 2 to complete this lesson and earn 15 XP.

  1. 1. Which loop guarantees that its body runs at least once?
  2. 2. Which statement skips the rest of the current iteration and starts the next one?
Answer every question to unlock the next lesson.