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

while Loop कैसे लिखें

एक while loop तब तक कुछ करता रहता है जब तक एक condition true रहे, जैसे गिलास भरते रहना जब तक वह भर न जाए। यह हर round से पहले जांचता है।

In this page:

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

while Loop

एक while loop हर iteration से पहले अपनी condition जांचता है और तब तक चलता रहता है जब तक यह true evaluate हो। यह तब आदर्श है जब iterations की संख्या पहले से ज्ञात न हो। अगर condition शुरू से false हो, तो body कभी execute नहीं होती।

Warning: body के अंदर loop variable को update करना भूल जाना एक infinite loop बनाता है।

उदाहरण: 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. #}
आम गलतियां
  1. condition variable को update करना भूल जाना, जो एक infinite loop का कारण बनता है।
  2. ऐसी condition लिखना जो शुरू से false हो, जिससे body कभी नहीं चलती।
  3. < के बजाय <= उपयोग करके off-by-one errors।
🔒

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.