← Back to C# Course | Chapter 4: Control Flow | Lesson 4 of 7

while Loop

In this page:

  1. while Loop

while Loop

A while loop checks its condition before every iteration and keeps running as long as it evaluates to true. It's ideal when the number of iterations isn't known ahead of time. If the condition starts false, the body never executes.

Warning: Forgetting to update the loop variable inside the body creates an infinite loop.

Example: while Loop

markup
using System;

class Program
{
    static void Main(string[] args)
    {
        int n = 20;
        int steps = 0;

        while (n > 1)
        {
            n = n % 2 == 0 ? n / 2 : n * 3 + 1;
            steps++;
        }

        Console.WriteLine($"Reached 1 in {steps} steps");
    }
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.