Skip to content

Beginner · Decisions, loops and methods · topic 7 of 43 · 30 min

Loops: for, while, do-while and foreach

Explanation

A loop repeats a block of code. Use for when you know how many times, while when you repeat until something changes, do-while when the body must run at least once, and foreach to visit every item in a collection. break leaves a loop early, and continue skips to the next round.

Why loops?

Computers are good at doing the same thing many times without getting tired. Printing 1,000 receipts, adding up a month of sales, or asking for a PIN until it is right are all loops. Without loops you would copy the same lines again and again.

Think of it like this: A loop is like counting laps on a school running track. The for loop is "run 4 laps". The while loop is "keep running while the whistle has not blown". The do-while loop is "run one lap, then check if the coach says stop".

The for loop

A for loop has three parts in its brackets, separated by semicolons: the start (int i = 1), the condition checked before every round (i <= 5), and the step done after every round (i++). Each round is called an iteration.

csharp
for (int i = 1; i <= 5; i++)
{
    Console.WriteLine($"5 x {i} = {5 * i}");
}
Prints the 5 times table from 5 x 1 = 5 to 5 x 5 = 25.
csharp
for (int i = 10; i > 0; i -= 3)
    Console.Write(i + " ");
Counting down in steps of 3: shows 10 7 4 1.

The while loop

while checks its condition BEFORE each round. If the condition is false at the start, the body never runs. Use it when you do not know in advance how many rounds you need.

csharp
decimal balance = 10000m;
int years = 0;
while (balance < 20000m)
{
    balance *= 1.08m;   // 8% interest per year
    years++;
}
Console.WriteLine($"Doubles in {years} years");
Shows Doubles in 10 years: at 8% a year, money passes double in the tenth year.

The do-while loop

do-while checks its condition AFTER each round, so the body always runs at least once. It fits menus and input checks, where you must ask at least once.

csharp
int pin;
do
{
    Console.Write("Enter 4-digit PIN: ");
} while (!int.TryParse(Console.ReadLine(), out pin) || pin < 1000 || pin > 9999);
Console.WriteLine("PIN accepted");
Asks again and again until the user types a 4-digit number.

The foreach loop

foreach visits every item of an array or collection, in order, without an index. It is the clearest loop when you just need each item.

csharp
string[] cities = { "Delhi", "Mumbai", "Kolkata", "Chennai" };
foreach (string city in cities)
{
    Console.WriteLine(city.ToUpper());
}
Shows each city in capital letters.
Careful: Inside foreach you cannot assign to the loop variable (city = "x" is error CS1656), and you must not add or remove items from a List while looping over it; that throws InvalidOperationException at run time. Use a for loop or build a new list instead.

break and continue

csharp
int[] amounts = { 120, -5, 300, 0, 9999, 80 };
foreach (int a in amounts)
{
    if (a <= 0) continue;     // skip bad values
    if (a > 5000) break;      // stop at a suspicious amount
    Console.WriteLine($"Processing Rs {a}");
}
Processes 120 and 300, skips -5 and 0, then stops at 9999, so 80 is never reached.

Nested loops

csharp
for (int row = 1; row <= 3; row++)
{
    for (int col = 1; col <= row; col++)
        Console.Write("*");
    Console.WriteLine();
}
A loop inside a loop. Shows a small triangle: *, **, ***.

Common mistakes and fixes

MistakeWhat happensFix
for (int i = 0; i <= arr.Length; i++)IndexOutOfRangeException on the last roundUse i < arr.Length; indexes go from 0 to Length - 1
while loop never changes its variableInfinite loop: the program hangsMake sure something in the body moves towards the end
Semicolon after the bracket: for (...);The loop body is empty; the block runs onceRemove the stray semicolon
Using i after the loopError: i does not exist hereDeclare i before the loop if you need it after
Tip: Press Ctrl + C in the terminal to stop a program stuck in an infinite loop.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Loops: for, while, do-while and foreach · 1/7

for · while · do-while · foreach

In this lesson you will repeat work with loops.

Prefer a video by a teacher? Find free videos on “C# loops for while do while foreach break continue tutorial” on YouTube ↗

In real life: A monthly recurring deposit at a post office

A post office recurring deposit (RD) adds a fixed amount every month. A simple loop shows how the money grows month by month. (Real RD interest is compounded quarterly at the rate the government sets; this shows only the loop idea with a simple monthly rate.)

csharp
decimal monthly = 2000m;
decimal monthlyRate = 0.006m;   // about 7.2% a year, for illustration
decimal balance = 0m;

for (int month = 1; month <= 12; month++)
{
    balance += monthly;
    balance += Math.Round(balance * monthlyRate, 2);
    if (month % 3 == 0)
        Console.WriteLine($"Month {month}: Rs {balance:F2}");
}
Prints the balance every 3 months; it grows a little faster each month because interest is earned on interest.

Practice (0/4 done)

Task 1 · Question

What does this print? for (int i = 0; i < 3; i++) Console.Write(i);

Task 2 · Question

int n = 10; while (n < 5) { Console.Write("x"); n++; } How many x are printed?

Task 3 · Question

int n = 10; do { Console.Write("x"); n++; } while (n < 5); How many x are printed?

Task 4 · Practice

Write an ATM PIN check. The correct PIN is 4321. Give the user 3 tries. On a correct PIN print "Welcome". After 3 wrong tries print "Card blocked". Use a loop with break.

Quick quiz

Question 1

1.Which loop always runs its body at least once?

Question 2

2.What does continue do?

Question 3

3.int[] a = {4, 5, 6}; Which loop condition is correct for indexes?

Question 4

4.What happens if you remove items from a List<T> inside a foreach over the same list?

Question 5

5.int sum = 0; for (int i = 1; i <= 4; i++) sum += i; What is sum?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Which loop always runs its body at least once?

Answer: do-while

do-while checks the condition after the body.

What does continue do?

Answer: Skips the rest of this round and starts the next one

continue jumps to the next iteration.

int[] a = {4, 5, 6}; Which loop condition is correct for indexes?

Answer: i < a.Length

Valid indexes are 0, 1, 2 (Length - 1), so loop while i < a.Length.

What happens if you remove items from a List<T> inside a foreach over the same list?

Answer: InvalidOperationException at run time

The list knows it was changed during enumeration and throws.

int sum = 0; for (int i = 1; i <= 4; i++) sum += i; What is sum?

Answer: 10

1 + 2 + 3 + 4 = 10.

Which loop always runs its body at least once?Related

Answer: do…while

do…while checks the condition after the first run.

From Loops: for, while, do…while, for…of and for…in

Which loop always runs its body at least once?Related

Answer: do-while

do-while checks its condition after the body.

From Loops: for, while, do-while and range-for

Which loop is best to visit every item of an array?Related

Answer: for...of

for...of gives you each item in turn, with no index to manage.

From Loops: repeating work

Which loop always runs its body at least once?Related

Answer: do-while

do-while checks the condition after the body.

From Loops and ranges

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 2 more topics in “Decisions, loops and methods” before its exam: Methods: write once, use many times, Parameters in depth: optional, named, ref, out, params, overloading.
  2. Module 2 exam: Decisions, loops and methods · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, Arrays, strings and null. 43 topics left in the course before the final exam.

← Previous: Decisions: if, else, switch and switch expressions