×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Scala for loop with multiple counters

By IncludeHelp Last updated : October 10, 2024

For loop is used to iterate over a block of code multiple times until a given condition is true. It is a counter-based loop that runs n times specified by a range.

In programming, their might arise cases where you need to iterate keeping in mind multiple counters (also known as generators in Scala) like in case of working with a multidimensional array.

How to use for loop with multiple counters?

It's a simple method, you just need to use two variables instead of one.

Syntax

for(i <- a to b ; j <- x to y)

// Or

for
{
  i <- a to b
  j <- x to y
}

Example to use for loop with multiple counter

object myObject {
    def main(args: Array[String]) {
       println("Printing elements using for loop with two iterators...")
       for(i <- 1 to 3; j <- 10 to 12)
            println(i+", "+j)
    }
}

Output

Printing elements using for loop with two iterators...
1, 10
1, 11
1, 12
2, 10
2, 11
2, 12
3, 10
3, 11
3, 12

Example to print 2-D array

object myObject {
    def main(args: Array[String]) {
        val array2D = Array.ofDim[Int](2,2)
        
        array2D(0)(0) = 3124
        array2D(0)(1) = 7895
        array2D(1)(0) = 9024
        array2D(1)(1) = 7612
        
        println("Elements of 2D array...")
        for(i <- 0 to 1; j <- 0 to 1)
            println("array("+i+", "+j+"): " + array2D(i)(j))
    }
}

Output

Elements of 2D array...
array(0, 0): 3124
array(0, 1): 7895
array(1, 0): 9024
array(1, 1): 7612

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.