Home » C programs » C One Dimensional Array programs

C program to check prime numbers in an array



In this C program, we are going to learn to check prime numbers in an array. We will declare an array with some prime and non prime numbers, and then print the elements with 'prime' and 'Not prime' message.
Submitted by IncludeHelp, on March 09, 2018

Given an array of integer elements and we have to check which prime numbers using C program are.

Example:

    Input:
    Array elements are: 
    100, 200, 31, 13, 97, 10, 20, 11

    Output:
    100 - Not Prime
    200 - Not Prime
     31 - Prime
     13 - Prime
     97 - Prime
     10 - Not Prime
     20 - Not Prime
     11 - Prime

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[loop]) – Here, loop is a loop counter.
  • Then we are checking a condition with print statement: (isPrime(arr[loop])?"Prime":"Not Prime") - This will return/print "Prime", if isPrime(arr[loop]) will return 1 or this will return/print "Not Prime", if isPrime(arr[loop]) will return 0.

Program to check prime numbers in 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 loop; //loop counter
	//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]);
	
	//print array elements with message 
	//"prime" or "Not prime"
	for(loop=0; loop<len; loop++)
	{
		printf("%3d - %s\n",arr[loop],(isPrime(arr[loop])?"Prime":"Not Prime"));
	}
	
	printf("\n");
	
	return 0;	
}

Output

100 - Not Prime
200 - Not Prime
 31 - Prime
 13 - Prime
 97 - Prime
 10 - Not Prime
 20 - Not Prime
 11 - Prime





Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.



Comments and Discussions





© https://www.includehelp.com (2015-2018), Some rights reserved.




close Like other websites, this site uses cookies to deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.