Introduction
Having just covered the powerful if statement, we’re going to move on to yet another very powerful construct in the C# language: loops. Loops allow you to repeat sections of code repeatedly. We’ll discuss three types of loops here in this tutorial, and we’ll cover the fourth type in the next tutorial when we discuss arrays (it makes a lot more sense with arrays).
Why do we need loops ?
In programming , writing the same line of code over and over is called redundancy, and it’s something programmers try to avoid at all costs.
1. The Efficiency Problem (DRY)
There is a famous rule in programming called DRY: Don’t Repeat Yourself without a loop: if you want to print “Hello” five times, you write Console.WriteLine("Hello") five times.
- With loop: you tell the computer “print hello”, and do it 5 times. if you later decide you want to change “hello” to “goodbye” you only have to change one line of code instead of five.
2. The scalability Problem What if you don’t know how many times you need to do something? If you are writing a program to process a list of customers, you might have 10 customers today, but 10,000 next month. You cannot manually write 10,000 lines of code. A loop allows your program to handle any amount of data by simply repeating the same logic until the work is done.
3. The Persistence Problem Most programs need to stay “alive” until the user decides to quit.
-
A video game needs to keep checking for input and updating the screen 60 times every second.
-
An ATM needs to stay on and wait for the next customer after the current one finishes. Without a loop (specifically an infinite or “forever” loop), a program would start, run its lines once, and immediately turn off.
-
The
ForLoop -
The
whileloop -
The
do/whileloop
The for Loop
The for loop is a powerful, compact ways to run a block of code a specific number of times. it is the “go-to” choice for counting or iterating through a fixed range.
1. The anatomy of a for loop
The for loop packs all the control logic into one line. It uses three distinct parts inside the parentheses, separated by semicolons:
/*
initial condition;
condition to check;
action at end of loop;
*/
for (initialization; condition; iterator )
{
// the code that runs every time.
}
- Initialization This runs once at the very beginning. It’s where you create your counter variable (
int x = 1;) - condition Before every “lap” of the loop, C# checks this. If it’s true, the loop runs. If false it stops (
x <= 10) - Iterator: This happens at the end of every lap. It’s usually where you update your counter (
x++)
Example classic “count to 10” example
for (int i = 1; i <= 10; i++)
{
Console.WriteLine("Number: " + i);
}
What happens here?
- Start:
iis set to 1. - Check: Is 1 less than or equal to 10? Yes.
- Work: Print “Number: 1”.
- Update:
i++makesibecome 2. - Repeat: It checks the condition again and continues until
ibecomes 11.
“counting down”
for (int i = 10; i >= 1; i--) {
Console.WriteLine("Number: " + i);
}
“Stepping”
for (int i = 0; i <= 20; i += 2) {
Console.WriteLine(i); // Prints 0, 2, 4, 6...
}
The while Loop
In programming we often need to repeat an action, but we don’t’ always know exactly how many times.
- an
ifstatement asks a question once and moves on. - A
whileloop asks a question, runs the code, and then goes back to ask the same question again. “As long as this remains true, do not stop”
1. The anatomy of a while loop
The while loop is the simplest looping structure in C#. It only cares about one thing the condition
while (condition)
{
// The "Body": Code that repeats
}
- The Entry Check: The program looks at the condition before entering the loop. If the condition is
falseat the very start, the code inside is never executed. - The Loop Cycle: If
true, the body runs. - The Re-evaluation: Once it hits the closing brace
}, it jumps back to thewhileline and checks the condition again.
Example The logic is spread out. you have to manually handle the starting point and the increment.
int x = 1; // 1. Initialization (Outside)
while (x <= 10) // 2. Condition
{
Console.WriteLine(x);
x++; // 3. Iterator (Inside the body)
}
2 times table
int count = 1;
while (count <= 10)
{
int result = 2 * count;
Console.WriteLine("2 X " + count + " = " + result);
count++;
}
The do while Loop
The do-while loop is a small but powerful variation of the while loop. The main difference is when the computer checks the condition.
The Key difference
whileloop: checks the condition before entering (might run 0 times).do-whileloop: checks the condition after the code runs (always runs at least 1 times).
syntax
notice that the “question” ( the while part) is at the very bottom, and it must end with a semicolon ;
int x = 100;
do {
Console.WriteLine("This runs even though x is 100!");
} while ( x < 10);
The biggest selling point of the do-while loop is the guarantee
- In a standard
whileloop, the code inside is a “maybe” it might never run. - In a
do-whileloop, the code is a “definitely” (at least once)
Analogy: Think of it like a vending machine.
whileloop: you check if you have money before you press the button. No money ? No snackdo-whileloop: you press he button first, then the machine checks if you have money. You always get a press that button once.
| Feature | for Loop | while Loop | do-while Loop |
|---|---|---|---|
| Main Purpose | Counting. When you know exactly how many laps to run. | Conditions. When you are waiting for something to happen. | Validation. When you must do the action at least once. |
| Check Time | Before the lap starts. | Before the lap starts. | After the lap finishes. |
| Minimum Runs | 0 | 0 | 1 |
| Control Logic | All in one line: (init; cond; step) | Spread out: Logic is usually inside the body. | Spread out: Check is at the very bottom. |
| Common Use | Printing tables, looping through arrays, grids. | Game loops, waiting for a “Quit” command. | Menus, asking for a password, user input. |
| Semicolon Rule | No semicolon at the end. | No semicolon at the end. | Must end with ; |
Loop Control statements
Think of a loop like a train on a circular track. Usually, it just keeps going around. break and continue are like the emergency breaks or a shortcut switch.
Break
The Break command stops the loop immediately. Once the computer hits a break it jumps out of the curly braces and moves on to the rest of the program.
- Real-life analogy: You are eating a box of 10 cookies. but you find a raisin in the 3rd one and decide to throw the whole box away.
for (int i = 1; i <= 10; i++)
{
if (i == 4)
{
break; // Stop everything!
}
Console.WriteLine("Eating cookie " + i);
}
// Output: Eating cookie 1, 2, 3... then it STOPS.
continue
The continute command skips the rest of the current lap and jumps straight to the start of the next one. The loop doesn’t stop; it just “skips” on turn.
- Real-life Analogy: you are eating a box of 10 cookies. You don’t’ like the 4th cookie, so you throw that one away but keep eating the 5th, 6th, 7th.
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
continue; // Skip the rest of this lap!
}
Console.WriteLine("Processing item " + i);
}
// Output: 1, 2, (skips 3), 4, 5.
| Command | What it does | Best Used For… |
|---|---|---|
break | Exit the loop forever. | Finding a specific item in a list or an “Exit Game” button. |
continue | Skip to the next lap. | Filtering out bad data (like skipping empty rows in a file). |
Nesting loops.
just like if statements, you can put one loop inside another. This is called Nesting
- the outer loop controls the Rows
- The inner loop controls the columns
The “Star Grid” example if we want to print a block of stars that is 5 rows tall and 10 columns wide, we use a nested loop:
for (int row = 0; row < 5; row++) // Outer Loop: Runs 5 times
{
for (int col = 0; col < 10; col++) // Inner Loop: Runs 10 times for EVERY row
{
Console.Write("*"); // Write stays on the same line
}
Console.WriteLine(); // Moves to the next line after the inner loop finishes
}
output
********** <- Row 0 (Inner loop ran 10 times)
********** <- Row 1 (Inner loop ran 10 times)
********** <- Row 2 (Inner loop ran 10 times)
********** <- Row 3 (Inner loop ran 10 times)
********** <- Row 4 (Inner loop ran 10 times)