Scala program to subtract an array from another array

Here, we are going to learn how to subtract an array from another array in Scala programming language?
Submitted by Nidhi, on May 26, 2021 [Last updated : March 10, 2023]

Scala – Subtracting One Array from Another Array

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.

Scala code to subtract an array from another array

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 IntArray1, IntArray2. 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.

Scala Array Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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