Home »
C programs »
C One Dimensional Array programs

# C program to delete prime numbers from an array

In this C program, we are going to learn **how can we check and delete prime numbers from an array**? We are declaring an array with some prime and non prime numbers and **deleting prime numbers and then printing array elements with the numbers which are not prime**.

Submitted by **IncludeHelp**, on March 09, 2018

**Given an array of integer elements and we have to remove prime numbers using C program.**

**Example:**

Input:
Array elements are:
100, 200, 31, 13, 97, 10, 20, 11
Output:
Array elements after removing prime numbers:
100
200
10
20

**Logic:**

- We are declaring an array (arr) with the elements: 100, 200, 31, 13, 97, 10, 20, 11
- To check prime numbers, we declare a function isPrime() that will return 1, if number is prime and return 0 if number is not prime.
- Then, in main() function – we are using a loop with 0 to len-1 (total number of array elements) and calling isPrime() by passing array elements one by one (arr[i]) – Here, i is a loop counter.
- Then, we are deleting the prime numbers, by checking elements using condition if(isPrime(arr[i])), if the condition is true, we are shifting other right side elements by one position left.
- Then, we are decreasing loop counter (i) by 1 to check the shifted element at the same place where prime number was exist.
- Then, we are decreasing the array size (len) by 1.
- Finally, we are printing the array elements – which are not primes.

## Program to remove prime numbers from an array using C program

#include <stdio.h>
//function to check number is prime or not
//function will return 1 if number is prime
int isPrime(int num)
{
int i; //loop counter
//it will be 1 when number is not prime
int flag=0;
//loop to check number is prime or not
//we will check, if number is divisible
//by any number from 2 to num/2, then it
//will not be prime
for(i=2; i<num/2; i++)
{
if(num%i ==0)
{
flag =1;
break;
}
}
//flag is 1, if number is not prime
if(flag==1)
return 0;
else
return 1;
}
int main()
{
int i,j; //loop counters
//declaring array with prime and not prime numbers
int arr[]={100, 200, 31, 13, 97, 10, 20, 11};
//calculate length of the array
int len = sizeof(arr)/sizeof(arr[0]);
//delete prime numbers
for(i=0; i<len; i++)
{
if(isPrime(arr[i]))
{
//number is prime, then shift other
//elements to the left
for(j=i; j<len; j++)
{
arr[j] = arr[j+1];
}
//decrease loop counter by 1,
//to check shifted element
i--;
//decrease the length
len--;
}
}
//print elements after removing prime numbers
printf("Array elements after removing prime numbers:\n");
for(i=0; i<len; i++)
printf("%3d\n",arr[i]);
printf("\n");
return 0;
}

**Output**

Array elements after removing prime numbers:
100
200
10
20