Start learning free

LESSON 114 OF 347 · WHILE LOOPS & FOR LOOPS

The while Loop in C#: Syntax, Flow and Counters

Lesson Read the full explanation

A while loop allows your program to perform a set of instructions as long as a condition is satisfied.

Here is the structure of a while loop:

while(condition) {
	instruction1
	instruction2
	...
}

Let's check an example:

int count = 1;
while(count <= 5) {
	Console.WriteLine("I made a mistake");
	count++;
}
Console.WriteLine("Finished!");

The output of this program is:

I made a mistake
I made a mistake
I made a mistake
I made a mistake
I made a mistake
Finished!

And this is what the computer does behind the scenes during this loop:

0. Creates and initializes a variable count = 1

1. First iteration:
	a. Is count <= 5 true? <=> Is 1 <= 5 true? Yes. 
	b. Console.WriteLine("I made a mistake"); => Output: I made a mistake
	c. count++; => count becomes 2
	
2. Second iteration:
	a. Is count <= 5 true? <=> Is 2 <= 5 true? Yes. 
	b. Console.WriteLine("I made a mistake"); => Output: I made a mistake
	c. count++; => count becomes 3
	
3. Third iteration:
	a. Is count <= 5 true? <=> Is 3 <= 5 true? Yes. 
	b. Console.WriteLine("I made a mistake"); => Output: I made a mistake
	c. count++; => count becomes 4
	
4. Forth iteration:
	a. Is count <= 5 true? <=> Is 4 <= 5 true? Yes. 
	b. Console.WriteLine("I made a mistake"); => Output: I made a mistake
	c. count++; => count becomes 5

5. Fifth iteration:
	a. Is count <= 5 true? <=> Is 5 <= 5 true? Yes. 
	b. Console.WriteLine("I made a mistake"); => Output: I made a mistake
	c. count++; => count becomes 6
	
6. Sixth iteration:
	a. Is count <= 5 true? <=> Is 6 <= 5 true? No. 
	b. Terminate the loop.

	
7. Console.WriteLine("Finished!"); => Output: Finished!

Pro Tip:

A while loop is essentally an if statement that repeats itself over and over until the condition becomes false.


Assignment

Let's print "I promise to learn coding" 5 times using a loop.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 4
    Ctrl + Enter to check

    C# · WHILE LOOPS & FOR LOOPS

    The While Loop in C#, explained

    What a while loop does

    A while loop runs a block of statements again and again, as long as a condition is true. You use it when you know the rule for stopping but not necessarily how many repetitions that takes, and also for simple counting, as in this lesson.

    while (condition) {
        // statements that repeat
    }
    

    The condition must be a bool expression, such as count <= 5. C# doesn't treat numbers as true or false, so while (1) doesn't compile. The braces hold the loop body.

    A first example

    int count = 1;
    while (count <= 5) {
        Console.WriteLine("I made a mistake");
        count++;
    }
    Console.WriteLine("Finished!");
    

    This prints I made a mistake five times, and then Finished! once. The loop has three ingredients, and a counting loop needs all of them:

    • Initialization. int count = 1; creates the variable before the loop starts.
    • Condition. count <= 5 is checked before every pass, including the first.
    • Update. count++ changes the variable inside the body, moving the loop toward the point where the condition is false.

    What the computer does

    CheckcountConditionAction
    111 <= 5 trueprint, count becomes 2
    222 <= 5 trueprint, count becomes 3
    333 <= 5 trueprint, count becomes 4
    444 <= 5 trueprint, count becomes 5
    555 <= 5 trueprint, count becomes 6
    666 <= 5 falseleave the loop

    After the sixth check, the program continues with the first statement after the closing brace, which prints Finished!. That statement runs once because it isn't part of the body.

    You can think of a while loop as an if statement that jumps back and asks the question again after each run of its body.

    Two behaviours worth knowing

    • The condition is checked first. If it is false at the very start, the body never runs. With int n = 10; and while (n < 5), nothing is printed.
    • The check happens only between passes. If the condition becomes false in the middle of the body, the rest of that pass still runs. The loop ends at the next check.

    Loops that don't count to a fixed number

    The condition doesn't have to compare against a constant count. A while loop can run until some state is reached. This one halves a number until it reaches 1, counting the halvings:

    int n = 100;
    int steps = 0;
    while (n > 1) {
        n /= 2;
        steps++;
    }
    Console.WriteLine(steps + " " + n);   // 6 1
    

    Here the number of passes isn't written anywhere in the code. It comes from the data. Integer division discards the remainder, so 100 becomes 50, 25, 12, 6, 3, 1. That's six passes. This is the kind of job a while loop suits best: you know when to stop, but not how many passes that takes in advance.

    The exercise, step by step

    The task is to print I promise to learn coding. five times using a loop.

    1. Declare the counter. int counter = 1; starts at 1, so the first pass counts as pass number 1.
    2. Write the loop header. while (counter <= 5) keeps going for the values 1, 2, 3, 4 and 5. That's five passes.
    3. Print inside the body. Console.WriteLine("I promise to learn coding."); runs on every pass.
    4. Update the counter. counter++; adds 1 after the print. Without it, counter stays 1, the condition is always true, and the loop never ends.
    int counter = 1;
    while (counter <= 5) {
        Console.WriteLine("I promise to learn coding.");
        counter++;
    }
    

    Common mistakes

    • Forgetting the update. This creates an infinite loop. The program keeps printing until you stop it.
    • Off-by-one errors. Starting at 0 with counter <= 5 prints six times. Starting at 1 with counter < 5 prints four times. Count the values the condition allows.
    • Using = instead of == or a comparison. In C#, while (counter = 5) is a compile error, because the assignment isn't a bool.
    • Putting a semicolon after the condition. while (counter <= 5); makes an empty loop body. The braces below it then run once, after the loop. The compiler warns about this.

    Key takeaways

    • while (condition) { ... } repeats its body as long as the condition is true.
    • A counting loop needs initialization, a condition and an update.
    • The condition is checked before every pass, so the body may run zero times.
    • If the update is missing, the loop never ends.
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free