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.
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.
Output:
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.
need an explanation for this answer? contact us directly to get an explanation for this answer