Question
Delete even position element from (array for java/ list for Python)
Input:
ENTER THE SIZE OF ARRAY:10
ENTER THE ELEMENT IN THE ARRAY:
1 2 3 4 5 6 7 8 9 10
ARRAY AFTER DELETING EVEN POSITION ELEMENTS:
2 4 6 8 10
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 DeleteEvenPositionElementFromArray
{
public static void main(String[] args)
{
/* Initialize array */
int [] arr;
int n=0,i=0,j=0,k=0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of array");
n = sc.nextInt();
arr=new int[n];
System.out.println("Enter numbers in array");
for(i=0;i< n;i++)
{
arr[i]=sc.nextInt();
}
for(i=0;i< n;i++)
{
if((i+1)%2==0)
{
arr[i]=-999998;
}
}
for(i=0;i< n;i++)
{
if(arr[i]==-999998)
{
k=i;
for(j=k+1;j< n;j++)
{
arr[k]=arr[j];
k++;
}
i=0;
n=n-1;
}
}
System.out.println("array after deleting even position");
for(i=0;i< n;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()))
count=0
#Print Given Elements
print("Elements in given List:")
print(li)
#counting the even postitions and
# changing value to "a"
#so that we can remove them easily afterwards
for i in range(1,size,2):
count=count+1
li[i]="a"
for i in range(0,count):
li.remove("a")
#You can also replace from line 14 to line 19 with
#li=[li[i] for i in range(0,size,2)]
#It will do the same thing
print("List after deleting even positions:")
print(li)