Write a C program to count the prime numbers in an array, In this C program example, we will learn Algorithm and C Code to count the prime numbers in an array.
Algorithm to count the prime numbers in an array
- Declare the main method
- Take array
- Check for prime number
- Count the prime number
C program to count the prime number in an array
#include<stdio.h> void main(){ int arr[100],i,a,j,b,count=0; printf("Enter size of an array:"); scanf("%d",&a); printf("Enter array elements:"); for (i=0;i<a;i++){ scanf("%d",&arr[i]); } printf("All prime list is:"); for(i=0;i<a;i++){ j=2; b=1; while(j<arr[i]){ if(arr[i]%j==0){ b=0; break; } j++; } if(b==1){ count=count+1; printf("%d ",arr[i]); } } printf("\nthe total prime number is %d ",count); }
Sample Input
10,13,21,27,19
Sample Output
The prime number is 13,19
The total prime number is 2
Explanation of this C program
Step 1 importing the library
Step 2 declare the main method using the void as its return type
Step 3 declare the variable and array
Step 4 command for the user to give size
Step 5 using the scanf method to take input
Step 6 command for user
Step 7, Step 8, Step 9 for loop to take input from user using scanf method and then closing the scope
Step 10 command for user
Step 11 for loop to access elements one by one
Step 12, Step 13 intialize the variable
Step 14 using a while loop to run the logic again and again
Step 15 checking the element whether it is greater than “j” the variable is declared
Step 16 if the condition satisfies the expression we update the variable “b” to 0
Step 17 break the condition
Step 18 closing the scope
Step 19 increment the “j” variable
Step 20 closing the scope of the while loop
Step 21 now the variable we updated before, here we check whether a variable is equal to 1
Step 22 increment in count variable to count the prime number
Step 23 print the element
Step24, Step 25 closing the scopes of other variables
Step 26 print the total prime number present in the array
Closing the loop
Output
In this blog, we learned how to create an array, find the prime number and then count them all