← Back to Scala Course | Chapter 4: Control Flow | Lesson 2 of 7

while लूप

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

In this page:

  1. while Loop
Syntax
scala
while (condition) {
  // body
}

while Loop

एक while loop हर iteration से पहले अपनी condition जांचता है और तब तक चलता रहता है जब तक यह true है। for के विपरीत, एक while loop खुद एक statement है जो Unit produce करता है, कोई उपयोगी value नहीं।

यह तब उपयोग होता है जब iterations की संख्या पहले से नहीं पता होती, हालांकि idiomatic Scala अक्सर practical होने पर while के बजाय higher-order functions या recursion को प्राथमिकता देता है।

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

उदाहरण: while Loop

markup
object Main extends App {
  var n = 20
  var steps = 0

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

  println(s"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. loop variable को update करना भूल जाना, जिससे while (n > 1) हमेशा चलता रहता है।
  2. counter के लिए val का उपयोग करना, जबकि loop के अंदर बदलने के लिए इसे var होना चाहिए।
  3. यह उम्मीद करना कि while एक value return करेगा, जबकि यह एक statement है जो Unit return करता है।
🔒

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.