Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added remove elements #16

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions remove elements
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// Java program to remove an element
// from a specific index from an array

import java.util.Arrays;

class GFG {

// Function to remove the element
public static int[] removeTheElement(int[] arr, int index)
{

// If the array is empty
// or the index is not in array range
// return the original array
if (arr == null || index < 0
|| index >= arr.length) {

return arr;
}

// Create another array of size one less
int[] anotherArray = new int[arr.length - 1];

// Copy the elements except the index
// from original array to the other array
for (int i = 0, k = 0; i < arr.length; i++) {

// if the index is
// the removal element index
if (i == index) {
continue;
}

// if the index is not
// the removal element index
anotherArray[k++] = arr[i];
}

// return the resultant array
return anotherArray;
}

// Driver Code
public static void main(String[] args)
{

// Get the array
int[] arr = { 1, 2, 3, 4, 5 };

// Print the resultant array
System.out.println("Original Array: "
+ Arrays.toString(arr));

// Get the specific index
int index = 2;

// Print the index
System.out.println("Index to be removed: " + index);

// Remove the element
arr = removeTheElement(arr, index);

// Print the resultant array
System.out.println("Resultant Array: "
+ Arrays.toString(arr));
}
}