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
Problem statement
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
Checking prime numbers in an array
- 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.
C program to check prime numbers in an array
#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
C One-Dimensional Array Programs »