Prime Number Program In C (3 Simple Ways)
In this article, we are going to write a Prime Number Program In C.
We will make this program in the following way -:
- Prime Number Program In C Using For Loop
- Prime Number Program In C Using While Loop
- Prime Number Program In C Using Do While Loop
To make this program, we will use the following concept given below.
If you do not know about these topics well, then you may not understand this program, so you should know about them in detail from the link given above.
Now without wasting time let’s start programming.
Prime Number Program In C Using For Loop
Algorithm
- Program start
- Declare Variable
- Loop start
- Check if condition
- Desplay result According to Condition
- Program End
Program
//C Program to check prime number Using For loop
#include <stdio.h>
int main()
{
int n, i, count = 0;
printf("Enter a number to check prime number or not : ");
scanf("%d",&n);
for(i=2; i<n; ++i)
{
// check for non prime number
if(n%i==0)
{
count=1;
break;
}
}
if (count==0)
printf("%d is a prime number.",n);
else
printf("%d is not a prime number.",n);
}
Output
Enter a number to check prime number or not : 5
5 is a prime number.
Prime Number Program In C Using While Loop
Program
//C Program for Prime Number Using While Loop
#include <stdio.h>
int main()
{
int n, i = 2, count = 0;
printf("Enter number to check prime number or not : ");
scanf("%d",&n);
while(i<n)
{
// check for non prime number
if(n%i==0)
{
count=1;
break;
}
i++;
}
if (count==0)
printf("%d is a prime number.",n);
else
printf("%d is not a prime number.",n);
}
Output
Enter number to check prime number or not : 17
17 is a prime number.
Prime Number Program In C Using Do While Loop
Program
//C program to check prime number using do while loop
#include <stdio.h>
int main()
{
int n, i = 2, count = 0;
printf("Enter a number to check prime number or not : ");
scanf("%d",&n);
do
{
// check for non prime number
if(n%i==0)
{
count=1;
break;
}
i++;
}while(i<n);
if (count==0)
printf("%d is a prime number.",n);
else
printf("%d is not a prime number.",n);
}
Output
Enter a number to check prime number or not : 9
9 is not a prime number.
Read More
- Download C Language Notes Pdf
- C Language Tutorial For Beginners
- C Programming Examples With Output
- 250+ C Programs for Practice PDF Free Download
Conclusion
So friends, in this article, we have written a Prime Number Program In C In this ways.
- Prime Number Program In C Using For Loop
- Prime Number Program In C Using While Loop
- Prime Number Program In C Using Do While Loop
If you have difficulty to understand any program or have any doubts or questions, then tell me in the comment below.