while और repeat-while Loops
एक while loop तब तक code दोहराता रहता है जब तक एक condition true रहे, और repeat-while वही करता है लेकिन पहले हमेशा code को कम से कम एक बार चलाता है।
In this page:
Syntax
while condition {
// body
}
repeat {
// body runs at least once
} while condition
Basic while Loop
एक while loop हर iteration से पहले अपना condition जांचता है, इसलिए इसकी body बिल्कुल नहीं चल सकती अगर condition शुरुआत में false हो।
उदाहरण: Basic while Loop
// Declare a mutable variable `countdown`, initialized to `3`
var countdown = 3
// Keep looping while `countdown > 0` holds
while countdown > 0 {
// Print "T-minus \(countdown)" to the console
print("T-minus \(countdown)")
countdown -= 1
}
// Print "Liftoff!" to the console
print("Liftoff!")
Login to try C/C++/Java/PHP code in the editor
repeat-while Loop
एक repeat-while loop body चलाने के बाद अपना condition जांचता है, गारंटी देते हुए कि body कम से कम एक बार execute होती है भले ही condition शुरुआत में false हो।
Note:
इसे body से पहले रखे उसी condition वाले एक
while loop से compare करें -- repeat-while हमेशा पहले एक बार चलता है।उदाहरण: repeat-while Loop
// Declare a mutable variable `attempts`, initialized to `0`
var attempts = 0
repeat {
attempts += 1
// Print "Attempt number \(attempts)" to the console
print("Attempt number \(attempts)")
} while attempts < 3
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. #}
आम गलतियां
- एक
whileloop लिखना जिसका condition कभी false नहीं होता, एक infinite loop बनाते हुए जो program को hang कर देता है। repeat-while(Swift का do-while version) को एक regularwhileके साथ confuse करना;repeat-whileहमेशा body को कम से कम एक बार execute करता है।- Loop के controlling variable को body के अंदर update करना भूल जाना, इसलिए condition कभी नहीं बदलता।
चैप्टर सारांश
while condition { }हर iteration से पहले condition जांचता है, संभवतः zero बार चलते हुए।repeat { } while conditionहर iteration के बाद condition जांचता है, हमेशा कम से कम एक बार चलते हुए।- दोनों loops को एक infinite loop से बचने के लिए condition को आखिरकार false होना चाहिए।
repeat-whileC-family languages में पाए जाने वालेdo-whileका Swift equivalent है।
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: