Question
DeleteĀ element from array divisible from number given by user
Input:
ENTER THE SIZE OF ARRAY:10
ENTER THE ELEMENT IN THE ARRAY:
1 2 3 4 5 6 7 8 9 10
ENTER THE DIVISOR:
5
ARRAY AFTER DELETING ELEMENTS:
1 2 3 4 6 7 8 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 DeleteElementFromArrayDivisibleByNumber
{
public static void main(String[] args)
{
/* Initialize array */
int [] arr;
int n=0,i=0,j=0,k=0,divisor=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();
}
System.out.println("Enter the divisor");
divisor=sc.nextInt();
for(i=0;i< n;i++)
{
if(arr[i]%divisor==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 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)
divisor=int(input("Enter the Divisor:"))
#counting the Element divisible by Divisor and
# changing value to "a"
#so that we can remove them easily afterwards
for i in range(0,size):
if(li[i]%divisor==0):
count=count+1
li[i]="a"
for i in range(0,count):
li.remove("a")
#You can also replace from line 15 to line 21 with
#li=[ele for ele in li if(ele%divisor!=0)]
#It will do the same thing
print("List after deleting odd positions:")
print(li)