Before going to write a c program for Prime number first you have to know about prime number , if statements, if-else statements.
A number that has factors as one and itself are known as prime numbers. For example number 3 has 1 and 3 as a factors and number 6 has 1, 2, 3, 6 as a factors. Therefore 3 is a Prime number and 6 is not a prime number.
To check a given number prime or not we have to use for loop and if ...else statements in c program. A positive number is said to be a prime number which is greater than 1 must have factors one and itself is called prime number.2, 3, 5, 7 etc. are prime numbers.
Now we will write an algorithm to Prime number.
Algorithm to check Prime number.
Example #1: Program to Check prime Number
A number that has factors as one and itself are known as prime numbers. For example number 3 has 1 and 3 as a factors and number 6 has 1, 2, 3, 6 as a factors. Therefore 3 is a Prime number and 6 is not a prime number.
To check a given number prime or not we have to use for loop and if ...else statements in c program. A positive number is said to be a prime number which is greater than 1 must have factors one and itself is called prime number.2, 3, 5, 7 etc. are prime numbers.
Now we will write an algorithm to Prime number.
Algorithm to check Prime number.
- Start.
- Input a number (say n)
- Divide number n from 0 to n.
- If n%2=0 increment count.
- If count=2 then print prime number.
- Else print not a prime number.
- Stop.
Example #1: Program to Check prime Number
#include<stdio.h>
main()
{
int i,n,count=0;
printf("Enter any number to check :");
scanf("%d",&n);
for(i=0;i<=n;i++)
{
if(n%i==0)
{
count++;
}
if(count==2)
printf("%d is prime number",n);
else
printf("%d is not a prime number",n);
}
Output:Enter any number to check :7
Given number is not a prime number
No comments