<style> .reveal-up, .reveal-left, .reveal-right, .reveal-stagger > * { opacity: 1 !important; transform: none !important; } </style>
  1. Learn
  2. C#
  3. Control flow
All lessons in this course

Lesson 9 of 60 15 minBeginner

Loops: for, while, do-while, foreach

Repeat work without copying code. See exactly how a loop runs, step by step, and learn which loop to choose.

Printing 1 to 100 with 100 WriteLine lines would be silly. A loop repeats a block of code while a condition is true. Each repetition is called an iteration.

The for loop

Use for when you know how many times to repeat. Its header has three parts separated by semicolons: start; condition; update.

Program.cs
for (int i = 1; i <= 5; i++){    Console.Write(i + " ");}
Output
1 2 3 4 5

The order is the important part: start runs once, then check → body → update → check → body → update… until the check is false. Step through it yourself:

Interactive

Run a loop step by step

This loop adds 1 + 2 + … + n. Press Step to watch the computer do one thing at a time.

ForLoop.cs
int n = 3;int sum = 0; for (int i = 1; i <= n; i++){    sum += i;} Console.WriteLine($"Sum = {sum}");
i?
sum0
i <= n–
Step 1 / 13
Before the loop: sum starts at 0. The loop variable i is created and set to 1. This happens only once.
Iterations so far
none yet

The while loop

Use while when you don’t know in advance how many times to repeat. You only know when to stop.

Doubling.cs
int money = 1000;int years = 0; while (money < 2000){    money += money * 10 / 100;   // 10% interest    years++;}Console.WriteLine($"Doubled after {years} years: {money}");
Output
Doubled after 8 years: 2142

The do-while loop

do...while checks the condition after the body, so the body always runs at least once. Perfect for “ask until the input is valid”.

AskAge.cs
int age;do{    Console.Write("Enter age (1-120): ");} while (!int.TryParse(Console.ReadLine(), out age) || age < 1 || age > 120); Console.WriteLine($"Thanks! Age = {age}");
Output
Enter age (1-120): abc
Enter age (1-120): 200
Enter age (1-120): 24
Thanks! Age = 24

The foreach loop

foreach visits every item of a collection (an array, a list, the characters of a string) without any index counting. It is the simplest and safest loop for reading items.

Program.cs
string[] members = { "Column", "Beam", "Brace" };foreach (string m in members){    Console.WriteLine($"Checking {m}");} foreach (char ch in "C#")    Console.WriteLine(ch);
Output
Checking Column
Checking Beam
Checking Brace
C
#

Which loop should I use?

LoopUse whenRuns at least once?
forYou know the count, or need the indexNo
whileYou repeat until something happensNo
do-whileThe body must run once first (menus, input)Yes
foreachYou read every item of a collectionNo

Counting down and stepping

Program.cs
for (int i = 10; i >= 0; i -= 2)    Console.Write(i + " ");
Output
10 8 6 4 2 0
Quick check

How many times does for (int i = 0; i < 5; i++) run its body?

Quick check

Which loop always runs its body at least once?

Practice

Print the multiplication table of a number entered by the user, from 1 to 10, like “7 x 3 = 21”.

Show the solution
Solution.cs
Console.Write("Number: ");int n = int.Parse(Console.ReadLine() ?? "0"); for (int i = 1; i <= 10; i++){    Console.WriteLine($"{n} x {i} = {n * i}");}
Output
Number: 7
7 x 1 = 7
7 x 2 = 14
...
7 x 10 = 70
Practice

Using a while loop, find how many digits a positive number has (e.g. 40512 has 5 digits).

Show a hint

Keep dividing by 10 with integer division and count how many times until the number becomes 0.

Show the solution
Solution.cs
int number = 40512;int digits = 0;while (number > 0){    number /= 10;    digits++;}Console.WriteLine(digits);
Output
5

Remember

  • for (start; condition; update): check → body → update, repeated.
  • while repeats while a condition is true; do-while runs at least once.
  • foreach reads every item in a collection without an index.
  • Always make sure the condition can become false, or the loop never ends.
0 of 60 lessons completed