Beginner · Decisions, loops and methods · topic 7 of 43 · 30 min
Loops: for, while, do-while and foreach
Explanation
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.
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.
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"5 x {i} = {5 * i}");
}for (int i = 10; i > 0; i -= 3)
Console.Write(i + " ");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.
decimal balance = 10000m;
int years = 0;
while (balance < 20000m)
{
balance *= 1.08m; // 8% interest per year
years++;
}
Console.WriteLine($"Doubles in {years} years");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.
int pin;
do
{
Console.Write("Enter 4-digit PIN: ");
} while (!int.TryParse(Console.ReadLine(), out pin) || pin < 1000 || pin > 9999);
Console.WriteLine("PIN accepted");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.
string[] cities = { "Delhi", "Mumbai", "Kolkata", "Chennai" };
foreach (string city in cities)
{
Console.WriteLine(city.ToUpper());
}break and continue
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}");
}Nested loops
for (int row = 1; row <= 3; row++)
{
for (int col = 1; col <= row; col++)
Console.Write("*");
Console.WriteLine();
}Common mistakes and fixes
| Mistake | What happens | Fix |
|---|---|---|
| for (int i = 0; i <= arr.Length; i++) | IndexOutOfRangeException on the last round | Use i < arr.Length; indexes go from 0 to Length - 1 |
| while loop never changes its variable | Infinite loop: the program hangs | Make sure something in the body moves towards the end |
| Semicolon after the bracket: for (...); | The loop body is empty; the block runs once | Remove the stray semicolon |
| Using i after the loop | Error: i does not exist here | Declare i before the loop if you need it after |
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
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.)
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}");
}Practice (0/4 done)
What does this print? for (int i = 0; i < 3; i++) Console.Write(i);
int n = 10; while (n < 5) { Console.Write("x"); n++; } How many x are printed?
int n = 10; do { Console.Write("x"); n++; } while (n < 5); How many x are printed?
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Methods: write once, use many timesDecisions, loops and methods · same module
- Parameters in depth: optional, named, ref, out, params, overloadingDecisions, loops and methods · same module
- Loops: for, while, do…while, for…of and for…inJavaScript Programming (language in depth) · Strings, decisions and loops
- Loops: for, while, do-while and range-forC++ Programming (modern C++ and DSA) · Decisions, loops and functions
- Loops: repeating workFrontend Web Development · JavaScript basics
- Loops and rangesKotlin and Android App Development · Kotlin basics
Questions people ask about this
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.
Which loop always runs its body at least once?Related
Answer: do-while
do-while checks its condition after the body.
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.
Which loop always runs its body at least once?Related
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
- 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.
- Module 2 exam: Decisions, loops and methods · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
- 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