0% found this document useful (0 votes)
4 views2 pages

Array Manipulation in Java

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)
4 views2 pages

Array Manipulation in Java

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

// Declare and initialize an array

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

// Display the original array


[Link]("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


[Link]("\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


[Link]("\nArray after update: ");
displayArray(myArray);

// Delete an element at a specific index


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

// Display the array after deletion


[Link]("\nArray after deletion: ");
displayArray(myArray);
}

// Function to display elements of the array


private static void displayArray(int[] arr) {
for (int value : arr) {
[Link](value + " ");
}
[Link]();
}

// Function to insert an element at a specific index


private static int[] insertElementAtIndex(int[] arr, int element, int index) {
int newArrLength = [Link] + 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 = [Link] - 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