Question
Delete even 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 ELEMENTS:
1 3 5 7 9
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 DeleteEvenElementFromArray
{
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(arr[i]%2==0)
{
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 element");
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 elements and
# changing value to "a"
#so that we can remove them easily afterwards
for i in range(0,len(li)):
if(li[i]%2==0):
count=count+1
li[i]="a"
for i in range(0,count):
li.remove("a")
# you can also replace from line 14 to line 20 with
# li=[ele for ele in li if(ele%2!=0)]
# it will do the same thing.
print("List after deleting element:")
print(li)