ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

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

Problem Solution:

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.

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.

Scala Array Programs »

ADVERTISEMENT




Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.