๐ŸŽ“ A1Learner
๐Ÿ”

C# While Loop

A while loop is a loop that repeats its block while its condition stays true. The condition is checked before each pass.

Counting up

The counter starts at 1. Each pass prints it and adds 1.

using System;

class Program
{
    static void Main(string[] args)
    {
        int i = 1;
        while (i <= 3)
        {
            Console.WriteLine(i);
            i++;
        }
    }
}

Counting down

The counter starts at 3. Each pass prints it and takes away 1.

using System;

class Program
{
    static void Main(string[] args)
    {
        int i = 3;
        while (i >= 1)
        {
            Console.WriteLine(i);
            i--;
        }
    }
}

A running sum

Each pass adds the counter to the sum. The sum reaches 10 after four passes.

using System;

class Program
{
    static void Main(string[] args)
    {
        int i = 1;
        int sum = 0;
        while (i <= 4)
        {
            sum += i;
            i++;
        }
        Console.WriteLine(sum);
    }
}

Example

using System;

class Program
{
    static void Main(string[] args)
    {
        int balance = 100;
        while (balance < 200)
        {
            balance += 25;
        }
        Console.WriteLine("Final balance: " + balance);
    }
}

Key points

  • The condition sits in parentheses after while.
  • The block runs again while the condition stays true.
  • A value in the condition must change inside the block.
  • The loop stops when the condition turns false.

In this example, balance starts at 100. Each pass adds 25 to it. The passes take it through 125, 150, and 175. The fourth pass reaches 200 and the condition turns false. The printed line is "Final balance: 200".

Note

A while loop runs zero times when its condition starts false.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C# Compiler

Exercise

When does a while loop check its condition?