Q:

Scala program to delete an item from the array

belongs to collection: Scala Array Programs

0

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

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

// Scala program to delete an item from array.

import scala.util.control.Breaks._

object Sample {
  def main(args: Array[String]) {
    var IntArray = Array(10, 20, 30, 40, 50, 60)
    var i: Int = 0
    var j: Int = 0

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

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

    // delete given item from array.
    breakable {
      flag = 0
      while (i < 6) {
        if (IntArray(i) == item) {
          flag = 1;
          j = i;
          while (j < 5) {
            IntArray(j) = IntArray(j + 1);
            j = j + 1;
          }
          break;
        }
        i = i + 1;
      }
    }
    if (flag == 1)
      printf("Item %d deleted successfully.\n", item)
    else
      printf("Item %d not found.\n", item)

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

Output:

Enter Item: 30
Item 30 deleted successfully.
Array Elements after deletion.
10 20 40 50 60

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 input item in the array and perform shift operations to overwrite the item in the array. After that, we printed the updated array 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 insert an item into an array... >>
<< Scala program to Cyclically Permutes the Elements ...