Home »
Scala »
Scala Programs
Scala program to delete an item from the array
Here, we are going to learn how to delete an item from the array in Scala programming language?
Submitted by Nidhi, on May 19, 2021 [Last updated : March 10, 2023]
Scala – Deleting an Item from Array
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.
Scala code to delete an item from the array
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.
Scala Array Programs »