Question
Delete an odd 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 ODD 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 DeleteOddElementFromArray
{
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 odd 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 odd 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 odd element:")
print(li)