← Back to Swift Course | Chapter 3: Control Flow | Lesson 5 of 8

while और repeat-while Loops

एक while loop तब तक code दोहराता रहता है जब तक एक condition true रहे, और repeat-while वही करता है लेकिन पहले हमेशा code को कम से कम एक बार चलाता है।
Syntax
swift
while condition {
    // body
}

repeat {
    // body runs at least once
} while condition

Basic while Loop

एक while loop हर iteration से पहले अपना condition जांचता है, इसलिए इसकी body बिल्कुल नहीं चल सकती अगर condition शुरुआत में false हो।

उदाहरण: Basic while Loop

markup
// 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!")

repeat-while Loop

एक repeat-while loop body चलाने के बाद अपना condition जांचता है, गारंटी देते हुए कि body कम से कम एक बार execute होती है भले ही condition शुरुआत में false हो।

Note: इसे body से पहले रखे उसी condition वाले एक while loop से compare करें -- repeat-while हमेशा पहले एक बार चलता है।

उदाहरण: repeat-while Loop

markup
// 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
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. एक while loop लिखना जिसका condition कभी false नहीं होता, एक infinite loop बनाते हुए जो program को hang कर देता है।
  2. repeat-while (Swift का do-while version) को एक regular while के साथ confuse करना; repeat-while हमेशा body को कम से कम एक बार execute करता है।
  3. Loop के controlling variable को body के अंदर update करना भूल जाना, इसलिए condition कभी नहीं बदलता।
चैप्टर सारांश
  • while condition { } हर iteration से पहले condition जांचता है, संभवतः zero बार चलते हुए।
  • repeat { } while condition हर iteration के बाद condition जांचता है, हमेशा कम से कम एक बार चलते हुए।
  • दोनों loops को एक infinite loop से बचने के लिए condition को आखिरकार false होना चाहिए।
  • repeat-while C-family languages में पाए जाने वाले do-while का Swift equivalent है।
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 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.