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

while Loop

A while loop keeps doing something for as long as a condition stays true, like refilling a glass until it is full. It checks before each round.

In this page:

  1. while Loop
Syntax
csharp
while (condition)
{
    // body
    // change something so the condition eventually becomes false
}

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");
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting to update the condition variable, causing an infinite loop.
  2. Writing a condition that is false from the start, so the body never runs.
  3. Off-by-one errors by using <= instead of <.
🔒

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.