Question
Delete Element from (array for java/ list for Python) at the position given by the user.
Enter size of array
5
Enter numbers in array
1:10
2:20
3:30
4:40
5:50
Elements given in Array:
10 20 30 40 50
Enter Position to be deleted:
3
array after deleting element in given position
10 20 40 50
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
Java
Python
Java
import java.util.Scanner;
public class DeleteElementFromGivenPositionArray
{
public static void main(String[] args)
{
/* Initialize array */
int [] arr;
int sizeOfArray=0,i=0,positionToBeDeleted=0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of array");
sizeOfArray = sc.nextInt();
arr=new int[sizeOfArray];
System.out.println("Enter numbers in array");
for(i=0;i< sizeOfArray;i++)
{
System.out.print((i+1)+":");
arr[i]=sc.nextInt();
}
System.out.println("Elements given in Array:");
for(i=0;i< sizeOfArray;i++)
{
System.out.print(arr[i]+" ");
}
System.out.println();
System.out.println("Enter Position to be deleted:");
positionToBeDeleted=sc.nextInt();
//We are Assuming that position given by user will start from 1
//but as indexing in array starts from zero so thats why we are
//Decreasing the value of positionToBeDeleted by 1
positionToBeDeleted=positionToBeDeleted-1;
if(positionToBeDeleted<0 ||positionToBeDeleted>=sizeOfArray)
{
System.out.println("Invalid position Entered");
}
else
{
for(i=positionToBeDeleted;i< sizeOfArray-1;i++)
{
arr[i]=arr[i+1];
}
sizeOfArray=sizeOfArray-1;
System.out.println("array after deleting element in given position");
for(i=0;i< sizeOfArray;i++)
{
System.out.print(arr[i]+" ");
}
}
}
}
Python
size=int(input("Enter the size of List:"))
li=[]
print("Enter Elements in list:")
for i in range(0,size):
print((i+1),end=": ")
li.append(int(input()))
#Print Given Elements
print("Elements in given List:")
print(li)
positionToBeDeleted=int(input("Enter the position to be Deleted:"))
"""
We are Assuming that position given by user will start from 1
but as indexing in list starts from zero so that is why we are
Decreasing the value of positionToBeDeleted by 1
"""
positionToBeDeleted=positionToBeDeleted-1
if(positionToBeDeleted<0 or positionToBeDeleted>=size):
print("Invalid position Entered")
else:
li.pop(positionToBeDeleted)
print("List after deleting element:")
print(li)