← Back to R Course | Chapter 4: Control Flow | Lesson 4 of 6

while Loop क्या है

एक while loop तब तक repeat होता रहता है जब तक इसकी condition true हो, sugar melt होने तक stir करने की तरह। Test हर lap से पहले आता है।

In this page:

  1. while Loop
Syntax
r
while (condition) {
  # body
}

while Loop

एक while loop हर iteration से पहले इसकी condition check करता है और जब तक यह TRUE हो चलता रहता है। यह तब इस्तेमाल होता है जब iterations की संख्या पहले से नहीं पता। अगर condition शुरू से FALSE है, body कभी execute नहीं होती।

Warning: body के अंदर loop variable update करना भूल जाना एक infinite loop बनाता है, बिल्कुल ज़्यादातर दूसरी languages की तरह।

उदाहरण: while Loop

markup
n <- 10
steps <- 0

while (n > 1) {
  if (n %% 2 == 0) {
    n <- n / 2
  } else {
    n <- n * 3 + 1
  }
  steps <- steps + 1
}

cat("Reached 1 in", steps, "steps\n")
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 बदलना भूल जाना, इसलिए while (n > 1) हमेशा के लिए loop करता है।
  2. condition में == की बजाय = इस्तेमाल करना।
  3. एक vector sum करने जैसी चीज़ के लिए while इस्तेमाल करना, जब sum() जैसे vectorised functions simpler हैं।
🔒

Chapter Quiz — Complete all 6 topics to unlock

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