CodeGym /Courses /C# SELF /while Loop: Getting to Know It and Some Gotchas

while Loop: Getting to Know It and Some Gotchas

C# SELF
Level 4 , Lesson 1
Available

1. Introduction

In programming, you often have to do the same thing over and over again. For example:

  • Go through all the elements of a list.
  • Read values from the keyboard until the user enters the right one.
  • Calculate the sum of all numbers from 1 to 100.
  • Ask the user for a password until they get it right.

If you try to do all this without loops, you'll end up with code that's long, boring, and impossible to scale. Imagine you're writing a calculator app and decide to add up numbers from 1 to 10 by hand:

int sum = 0;
sum += 1;
sum += 2;
sum += 3;
// ... and so on, 10 times. Yikes.
Manually repeating without a loop — not fun!

You'd get bored before you finish! The solution is loops. They let you describe repeated actions in a short and clear way. Today, we're gonna meet the most basic, but super useful loop — while.

2. Getting to Know the while Loop

Syntax and Basic Structure

The while loop is like a "parrot" in the programming world: it repeats the same chunk of code as long as some condition is true. As soon as the condition stops being true, the parrot shuts up (the loop ends).


while (condition)
{
    // Loop body
}
while loop with a block of commands

Diagram

Here's a simple flowchart to help you get how the while loop works:

3. Examples: while Loop in Action

Classic Counter

Let's make a simple program that counts from 1 to 5 and prints the numbers:

int i = 1;
while (i <= 5)
{
    Console.WriteLine($"Step # {i}");
    i++; // Don't forget to increment the counter!
}
// Output:
// Step # 1
// Step # 2
// Step # 3
// Step # 4
// Step # 5

Notice: if you forget to increment the i variable, the loop will never end (our parrot becomes immortal and repeats forever). This is called an infinite loop — kinda scary.

Input from Keyboard Until the Right Value

It's pretty common to use a loop to "push" the user until they give the right answer:

string password = "";
while (password != "qwerty")
{
    Console.Write("Enter password: ");
    password = Console.ReadLine();
}
Console.WriteLine("Welcome!");

Here, the program asks for a password until you type the magic "qwerty". Don't forget: if you remove the line password = Console.ReadLine();, the loop will be infinite again (it'll keep asking for the password but never read input — stuck forever, like a broken robot).

4. Types and Use Cases for the while Loop

Regular while Loop

This loop, like we saw above, checks the condition before the first iteration. If the condition is false right away — the loop body won't run even once.

Example: condition is false right away

int i = 10;
while (i < 5)
{
    Console.WriteLine(i); // This will never run!
}

Which, honestly, makes sense. That's exactly how it's supposed to work.

Nested while Loops

Sometimes you need a loop inside a loop. For example, go through all the lines, and in each one check all the characters. At this stage, it's kinda wild, but here's a simple example:

int i = 1;
while (i <= 3)
{
    int j = 1;
    while (j <= 2)
    {
        Console.WriteLine($"i = {i}, j = {j}");
        j++;
    }
    i++;
}

// i = 1, j = 1
// i = 1, j = 2
// i = 2, j = 1
// i = 2, j = 2
// i = 3, j = 1
// i = 3, j = 2

We'll dig into nested loops in more detail in a couple of lectures, just wanted to spook you a bit :)

Infinite Loop

Sometimes loops end, and sometimes — they live forever.

while (true)
{
    Console.WriteLine("I am eternal!");
}

It's used rarely, usually for some background processes (like a server running), but it does happen in real life.

5. How Not to Mess Up: Common while Loop Mistakes

In programming, a loop is like electricity: awesome, but you gotta know the safety rules.

Problem 1: Infinite Loop by Accident

Newbies often forget to update the variable that the condition depends on. As a result, the loop runs "forever", and you have to force-stop the program (for example, with Ctrl + C).

int i = 1;
while (i <= 5)
{
    Console.WriteLine(i);
    // i++;  // OOPS! Forgot to increment i
}

Problem 2: Wrong Condition

Sometimes a developer digs their own hole: the condition is never true. As a result, the loop doesn't run at all.

int i = 10;
while (i < 5)
{
    Console.WriteLine(i); // This code will never run.
    i++;
}

Problem 3: Data Type Error

The loop condition always has to be a boolean expression — meaning the result should be true or false.

int number = 5;
while (number) // Error! Expected bool, not int.
{
    number--;
}
2
Task
C# SELF, level 4, lesson 1
Locked
Printing numbers from 1 to 10
Printing numbers from 1 to 10
2
Task
C# SELF, level 4, lesson 1
Locked
Sum of numbers up to a given limit
Sum of numbers up to a given limit
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION