0% found this document useful (0 votes)
8 views

Array

Uploaded by

Micah Okpara
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Array

Uploaded by

Micah Okpara
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

// Declare and initialize an array

int[] myArray = {1, 2, 3, 4, 5};

// Display the original array


System.out.println("Original Array: ");
displayArray(myArray);

// Insert an element at a specific index


int insertElement = 10;
int insertIndex = 2;
myArray = insertElementAtIndex(myArray, insertElement, insertIndex);

// Display the array after insertion


System.out.println("\nArray after insertion: ");
displayArray(myArray);

// Update an element at a specific index


int updateElement = 8;
int updateIndex = 3;
updateElementAtIndex(myArray, updateElement, updateIndex);

// Display the array after update


System.out.println("\nArray after update: ");
displayArray(myArray);

// Delete an element at a specific index


int deleteIndex = 1;
myArray = deleteElementAtIndex(myArray, deleteIndex);

// Display the array after deletion


System.out.println("\nArray after deletion: ");
displayArray(myArray);
}

// Function to display elements of the array


private static void displayArray(int[] arr) {
for (int value : arr) {
System.out.print(value + " ");
}
System.out.println();
}

// Function to insert an element at a specific index


private static int[] insertElementAtIndex(int[] arr, int element, int index) {
int newArrLength = arr.length + 1;
int[] newArr = new int[newArrLength];

for (int i = 0, j = 0; i < newArrLength; i++) {


if (i == index) {
newArr[i] = element;
} else {
newArr[i] = arr[j++];
}
}

return newArr;
}

// Function to update an element at a specific index


private static void updateElementAtIndex(int[] arr, int element, int index) {
arr[index] = element;
}

// Function to delete an element at a specific index


private static int[] deleteElementAtIndex(int[] arr, int index) {
int newArrLength = arr.length - 1;
int[] newArr = new int[newArrLength];

for (int i = 0, j = 0; i < newArrLength; i++) {


if (i == index) {
j++; // Skip the element at the specified index
}
newArr[i] = arr[j++];
}

return newArr;

You might also like