Scala program to access array elements using foreach loop

Here, we are going to learn how to access array elements using foreach loop in Scala programming language?
Submitted by Nidhi, on May 07, 2021 [Last updated : March 10, 2023]

Scala – Access Array Elements using Foreach Loop

Here, we will create an array of 5 integer elements using the new keyword. And, we will read array elements from the user and access array elements using the foreach loop and print on the console screen.

Scala code to access array elements using foreach loop

The source code to access array elements using the foreach loop is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to access array elements 
// using foreach loop

object Sample {  
    def main(args: Array[String]) {  
        // Create an array with 5 integer elements
        var MyArr = new Array[Int](5) 
        var count:Int=0
        
        println("Enter array elements:")
        while(count<5)
        {
            printf("Eelemnt[%d]: ",count);
            MyArr(count)=scala.io.StdIn.readInt();
            
            count=count+1;
        }
        
        // Access each element of array.
        println("Elements of array:")
        MyArr.foreach((item:Int)=>printf("%d ",item))  
        
        println()
    }
}  

Output

Enter array elements:
Eelemnt[0]: 50
Eelemnt[1]: 40
Eelemnt[2]: 30
Eelemnt[3]: 20
Eelemnt[4]: 10
Elements of array:
50 40 30 20 10

Explanation

In the above program, we used an object-oriented approach to create the program. We created an object Sample, and we defined main() function. The main() function is the entry point for the program.

In the main() function, we created an integer array MyArr with 5 elements using the new keyword. Then we read array elements from the user. After that, we accessed elements of the array using the foreach loop and printed all elements on the console screen.

Scala Array Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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