Scala program to add two integer arrays

Here, we are going to learn how to add two integer arrays in Scala programming language?
Submitted by Nidhi, on May 26, 2021 [Last updated : March 10, 2023]

Scala – Adding Elements of Two Arrays

Here, we will create two arrays of integer elements then we add elements of both arrays and print the resulted array on the console screen.

Scala code to add two elements of integer arrays

The source code to add two integer arrays is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to add two integer arrays

object Sample {
  def main(args: Array[String]) {
    var IntArray1 = Array(10, 20, 30, 40, 50)
    var IntArray2 = Array(11, 21, 31, 41, 51)
    var IntArray3 = new Array[Int](5)
    var i: Int = 0

    println("Elements of IntArray1: ");
    i = 0;
    while (i < 5) {
      printf("%d ", IntArray1(i));
      i = i + 1;
    }
    println()

    println("\nElements of IntArray2: ");
    i = 0;
    while (i < 5) {
      printf("%d ", IntArray2(i));
      i = i + 1;
    }
    println()

    i = 0;
    while (i < 5) {
      IntArray3(i) = IntArray1(i) + IntArray2(i);
      i = i + 1;
    }

    println("\nAddition of IntArray1 and IntArray2: ");
    i = 0;
    while (i < 5) {
      printf("%d ", IntArray3(i));
      i = i + 1;
    }
    println()
  }
}

Output

Elements of IntArray1: 
10 20 30 40 50 

Elements of IntArray2: 
11 21 31 41 51 

Addition of IntArray1 and IntArray2: 
21 41 61 81 101

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 two arrays IntArray1, IntArray2.  Each array contains 5 integer items. Then we added elements of IntArray1 with IntArray2 and assigned the result into IntArray3. After that, we printed all arrays on the console screen.

Scala Array Programs »



Related Programs



All Scala Programs

Comments and Discussions!

Load comments ↻





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