Q:

Scala program to access array elements using foreach loop

belongs to collection: Scala Array Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala Array Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Scala program to get the size of an array... >>
<< Scala program to create an integer array using the...