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

for लूप

एक for loop एक-एक करके values के एक सेट से गुजरता है, जैसे अपनी उंगलियों पर एक से पांच तक गिनना। variable बारी-बारी से हर value लेता है।

In this page:

  1. for Loop
Syntax
scala
for (i <- start to end) {
  // body
}

for (item <- collection) {
  // body
}

for Loop

एक basic for loop, for (i <- 1 to 5) { ... }, किसी Range या किसी collection पर iterate करता है, हर element के लिए एक बार block चलाता है। to अपने endpoint को शामिल करता है जबकि until उसे बाहर रखता है।

यह सरल form एक statement है जो Unit produce करता है, और सिर्फ printing जैसे side effects के लिए उपयोग होता है।

Note: 1 until 5 5 को बाहर रखता है, जबकि 1 to 5 उसे शामिल करता है -- एक नज़र में इन्हें मिला देना आसान है।

उदाहरण: for Loop

markup
object Main extends App {
  for (i <- 1 to 5) {
    println(s"Count: $i")
  }

  for (i <- 0 until 3) {
    println(s"Zero-based: $i")
  }
}
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. 1 to 5 का उपयोग करना और यह उम्मीद करना कि आखिरी number बाहर रहेगा, जबकि to में 5 शामिल है और until में नहीं।
  2. for (i = 0; i < 5; i++) जैसी C-style syntax का उपयोग करना, जो Scala में मौजूद नहीं; for (i <- 0 until 5) का उपयोग करें।
  3. body के अंदर loop variable बदलने की कोशिश करना, जबकि i एक val है और reassign नहीं किया जा सकता।
🔒

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.