while Loop कैसे लिखें
एक while loop तब तक कुछ करता रहता है जब तक एक condition true रहे, जैसे गिलास भरते रहना जब तक वह भर न जाए। यह हर round से पहले जांचता है।
In this page:
Syntax
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
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");
}
}
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
- condition variable को update करना भूल जाना, जो एक infinite loop का कारण बनता है।
- ऐसी condition लिखना जो शुरू से false हो, जिससे body कभी नहीं चलती।
<के बजाय<=उपयोग करके off-by-one errors।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: