Scala program to insert an item into an array

Here, we are going to learn how to insert an item into an array in Scala programming language?
Submitted by Nidhi, on May 19, 2021 [Last updated : March 10, 2023]

Scala – Inserting an Item into an Array

Here, we will create an array of integers and then we will insert an item into the array and print the updated array on the console screen.

Scala code to insert an item into an array

The source code to insert an item into the array is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to insert an item into the array.
import scala.util.control.Breaks._
object Sample {

  def main(args: Array[String]) {
    var IntArray = new Array[Int](6)
    var i: Int = 0
    var j: Int = 0

    var item: Int = 0
    var flag: Int = 0

    IntArray(0) = 10;
    IntArray(1) = 20;
    IntArray(2) = 30;
    IntArray(3) = 40;
    IntArray(4) = 50;

    print("Enter Item: ")
    item = scala.io.StdIn.readInt();

    // Insert item into array.
    breakable {
      i = 0
      while (i < 6) {
        if (IntArray(i) >= item) {
          j = 4;
          while (j >= i) {
            IntArray(j + 1) = IntArray(j);
            j = j - 1;
          }
          IntArray(i) = item;
          break;
        }
        i = i + 1;
      }
    }

    i = 0;
    printf("Array Elements after insertion.\n")
    while (i < 6) {
      printf("%d ", IntArray(i));
      i = i + 1;
    }
    println();
  }
}

Output

Enter Item: 35
Array Elements after insertion.
10 20 30 35 40 50

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 array IntArray that contains 6 integer items. Then we read an item from the user. Then we find the array element, which is greater than the input item. After that, we performed a shift operation to insert an item at the correct location, and then we printed the updated array 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.