ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Scala program to create an integer array using the new keyword

Here, we are going to learn how to create an integer array using the new keyword 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. We will read and print elements of the array using loops.

Program/Source Code:

The source code to create an integer array using the "new" keyword is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to create an array using "new" keyword

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:")
        for(item<-MyArr)                     
            printf("%d ",item)  
        println()
    }
}  

Output:

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

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 and accessed each element from the array using the for 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.