import java.util.Scanner;
public class ArrayInsertionMenu {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] arr = new int[100];
int n, i, choice, value, pos;
System.out.print("Enter number of elements: ");
n = sc.nextInt();
System.out.println("Enter elements:");
for(i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
System.out.println("\nChoose Insertion Type:");
System.out.println("1. Insert at Beginning");
System.out.println("2. Insert at End");
System.out.println("3. Insert at Specific Position");
choice = sc.nextInt();
switch(choice) {
case 1:
System.out.print("Enter value: ");
value = sc.nextInt();
for(i = n; i > 0; i--) {
arr[i] = arr[i - 1];
}
arr[0] = value;
n++;
break;
case 2:
System.out.print("Enter value: ");
value = sc.nextInt();
arr[n] = value;
n++;
break;
case 3:
System.out.print("Enter position: ");
pos = sc.nextInt();
System.out.print("Enter value: ");
value = sc.nextInt();
for(i = n; i > pos; i--) {
arr[i] = arr[i - 1];
}
arr[pos] = value;
n++;
break;
default:
System.out.println("Invalid choice!");
}
System.out.println("\nArray after insertion:");
for(i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.