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.
Program/Source Code:
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.
Output:
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.
need an explanation for this answer? contact us directly to get an explanation for this answer