Loops: for, while, do and foreach
Course contents (16 lessons)
- Getting started
- Installing the .NET 10 SDK and checking it works
- Your first console app and top-level statements
- The building blocks
- Variables and basic types
- Working with strings and interpolation
- Reading input and writing output
- Making decisions and repeating work
- Conditionals and switch expressions
- Loops: for, while, do and foreach
- Collections and methods
- Arrays and List of T
- Writing your own methods
- Objects and classes
- Classes and objects
- Properties, encapsulation and object initialisers
- Handling null safely
- Errors and files
- Exceptions: try, catch, finally and throw
- Reading and writing files
- Final project: expense tracker
- Expense tracker, part 1: planning, model and storage
- Expense tracker, part 2: the menu and summaries
Doing something many times
Imagine printing the numbers from 1 to 100. You would not write 100 lines. You write a loop. A loop repeats a block of code while some condition holds. C# gives you four kinds. Each fits a different situation.
for: when you know how many times
A for loop has three parts in the brackets: where to start, when to continue, and what to do after each round.
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"Round {i}");
}
Read it aloud: start with i at 1, keep going while i is at most 5, and add 1 to i after each round. The operator i++ means "add one". The variable i only exists inside the loop.
while: when you do not know how many times
A while loop checks its condition before each round. Use it when the number of rounds depends on something that happens during the loop, such as user input.
do-while: at least once
A do-while loop runs the body first and checks the condition afterwards. That guarantees at least one round. It is good for menus: show the menu, read a choice, repeat unless the user chose to quit.
foreach: for every item in a collection
When you have an array or a list and want to visit every item, foreach is the cleanest. It has no counter to get wrong. We use it a lot in the next lesson.
// for: a multiplication table
Console.Write("Table of which number? ");
int.TryParse(Console.ReadLine(), out int n);
for (int i = 1; i <= 10; i++)
{
Console.WriteLine($"{n} x {i,2} = {n * i,3}");
}
// while: guess the number
int secret = Random.Shared.Next(1, 11);
int guess = 0;
int tries = 0;
while (guess != secret)
{
Console.Write("Guess a number from 1 to 10: ");
int.TryParse(Console.ReadLine(), out guess);
tries++;
}
Console.WriteLine($"Correct, after {tries} tries.");
// do-while: a tiny menu
string choice;
do
{
Console.WriteLine();
Console.WriteLine("1) Say hello");
Console.WriteLine("2) Say goodbye");
Console.WriteLine("q) Quit");
Console.Write("Choose: ");
choice = Console.ReadLine() ?? "q";
if (choice == "1") Console.WriteLine("Hello!");
else if (choice == "2") Console.WriteLine("Goodbye!");
}
while (choice != "q");
// foreach with continue
string[] names = { "Ali", "", "Sara", "Hamza" };
foreach (string name in names)
{
if (name == "")
{
continue;
}
Console.WriteLine($"Hello, {name}");
}
Walking through it
The multiplication table uses {i,2} and {n * i,3} so the columns line up. That is the width option from the strings lesson.
The guessing game has no fixed count. Random.Shared.Next(1, 11) gives a number from 1 to 10. The upper bound is exclusive, which surprises many beginners. The loop runs until guess equals secret. Note that guess starts at 0 so the condition is false-to-start-looping. If the user types letters, TryParse sets guess to 0 and they simply get asked again.
The menu loop reads the choice at the end of each round, and the while condition at the bottom decides whether to go again. Notice that choice is declared before the loop. Variables declared inside the braces cannot be seen in the condition at the bottom.
The last loop uses continue, which skips the rest of the current round and jumps to the next. Its sibling break leaves the loop entirely.
Common mistakes
- Infinite loops. If the condition can never become false, the program hangs. Press Ctrl+C to stop it. Check that something inside the loop changes the condition.
- Off-by-one errors. Is it
<or<=? Run through the first and last round on paper. - Changing a collection while using foreach on it. Adding or removing items inside the loop throws an exception.
- Declaring the variable inside the loop and then needing it after.
Try it yourself
- Print all even numbers from 2 to 50.
- Calculate the sum of the numbers from 1 to 100 using a loop. Check your answer against the formula n * (n + 1) / 2.
- Print a right-angled triangle of stars, five rows high. You will need one loop inside another.
- Change the guessing game to tell the player "higher" or "lower" after each wrong guess.
// for: a multiplication table
Console.Write("Table of which number? ");
int.TryParse(Console.ReadLine(), out int n);
for (int i = 1; i <= 10; i++)
{
Console.WriteLine($"{n} x {i,2} = {n * i,3}");
}
// while: guess the number
int secret = Random.Shared.Next(1, 11);
int guess = 0;
int tries = 0;
while (guess != secret)
{
Console.Write("Guess a number from 1 to 10: ");
int.TryParse(Console.ReadLine(), out guess);
tries++;
}
Console.WriteLine($"Correct, after {tries} tries.");
// do-while: a tiny menu
string choice;
do
{
Console.WriteLine();
Console.WriteLine("1) Say hello");
Console.WriteLine("2) Say goodbye");
Console.WriteLine("q) Quit");
Console.Write("Choose: ");
choice = Console.ReadLine() ?? "q";
if (choice == "1") Console.WriteLine("Hello!");
else if (choice == "2") Console.WriteLine("Goodbye!");
}
while (choice != "q");
// foreach with continue
string[] names = { "Ali", "", "Sara", "Hamza" };
foreach (string name in names)
{
if (name == "")
{
continue;
}
Console.WriteLine($"Hello, {name}");
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account