Q:

Scala program to subtract an array from another array

belongs to collection: Scala Array Programs

0

Here, we will create two arrays of integer elements then we will subtract an array from another array and assign the result to the third array.

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 subtract an array from another array is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to subtract an array
// from another array

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 Array1: ");
    i = 0;
    while (i < 5) {
      printf("%d ", IntArray1(i));
      i = i + 1;
    }
    println()

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

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

    println("\nResulted array: ");
    i = 0;
    while (i < 5) {
      printf("%d ", IntArray3(i));
      i = i + 1;
    }
    println()
  }
}

Output:

Elements of Array1: 
10 20 30 40 50 

Elements of Array2: 
11 21 31 41 51 

Resulted array: 
1 1 1 1 1

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 IntArray1IntArray2. Each array contains 5 integer items. Then we subtracted the elements of IntArray1 from IntArray2 and assigned the result into IntArray3. After that, we printed all arrays 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 add two matrices... >>
<< Scala program to add two integer arrays...