Operation on Arrays in Data Structure: Traversal, Insertion, Deletion and Searching
import java.util.Scanner;
class ArrayOperations {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] arr = {1, 2, 4, 5};
while (true) {
System.out.println("Select an operation:");
System.out.println("1. Traversal");
System.out.println("2. Insertion");
System.out.println("3. Deletion");
System.out.println("4. Searching");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
traverseArray(arr);
break;
case 2:
arr = insertElement(arr, scanner);
break;
case 3:
arr = deleteElement(arr, scanner);
break;
case 4:
searchElement(arr, scanner);
break;
case 5:
System.out.println("Exiting program.");
scanner.close();
System.exit(0);
default:
System.out.println("Invalid choice. Please try again.");
break;
}
}
}
// Function to traverse and print the array elements
public static void traverseArray(int[] arr) {
System.out.println("Traversal:");
for (int element : arr) {
System.out.print(element + " ");
}
System.out.println();
}
// Function to insert an element into the array
public static int[] insertElement(int[] arr, Scanner scanner) {
System.out.print("Enter the index to insert: ");
int index = scanner.nextInt();
System.out.print("Enter the value to insert: ");
int valueToInsert = scanner.nextInt();
// Insertion
int[] newArr = new int[arr.length + 1];
for (int i = 0, j = 0; i < newArr.length; i++) {
if (i == index) {
newArr[i] = valueToInsert;
} else {
newArr[i] = arr[j++];
}
}
return newArr;
}
// Function to delete an element from the array
public static int[] deleteElement(int[] arr, Scanner scanner) {
System.out.print("Enter the index to delete: ");
int indexToDelete = scanner.nextInt();
// Deletion
int[] newArr = new int[arr.length - 1];
for (int i = 0, j = 0; i < arr.length; i++) {
if (i == indexToDelete) {
continue; // Skip the element to be deleted
}
newArr[j++] = arr[i];
}
return newArr;
}
// Function to search for an element in the array
public static void searchElement(int[] arr, Scanner scanner) {
System.out.print("Enter the element to search for: ");
int target = scanner.nextInt();
// Searching
boolean found = false;
for (int element : arr) {
if (element == target) {
found = true;
break;
}
}
if (found) {
System.out.println("Element " + target + " found.");
} else {
System.out.println("Element " + target + " not found.");
}
}
}
Comments
Post a Comment