Enter your email address:


Monday, September 2, 2013

Home » , » Write a program to check whether the given number is a prime.

Write a program to check whether the given number is a prime.

Questions: Top-30-c-programs-asked-in-interview_6304.html

8. Write a program to check whether the given number is a prime.
A prime number is a natural number that has only one and itself as factors. Examples: 2, 3, 13 are prime
numbers.
Program:
#include
main(){
int n, i, c = 0;
printf("En ter any number n: \n");
scanf("%d" ,&n);
/*logic*/
for (i = 1; i
if (n % i == 0){
c++;
}
}
if (c == 2){
printf("n is a Prime number");
}
else{
printf("n is not a Prime number");
}
return 0;
}
Output:
Enter any number n: 7
n is Prime
Explanatio n with examples:
consider a number n=5
for(i=0;i
i.e. for(i=0;i
1st iteration: i=1;i
here i is incremente d i.e. i value for next iteration is 2
now if(n%i==0) then c is incremente d
i.e.if(5%1 ==0)then c is incremente d, here 5%1=0 thus c is incremente d.
now c=1;
2nd iteration: i=2;i
here i is incremente d i.e. i value for next iteration is 3
now if(n%i==0) then c is incremente d
i.e.if(5%2 ==0) then c is incremente d, but 5%2!=0 and so c is not incremente d, c remains 1
c=1;
3rd iteration: i=3;i
here i is incremente d i.e. i value for next iteration is 4
now if(n%i==0) then c is incremente d
i.e.if(5%3 ==0) then c ic incremente d, but 5%3!=0 and so c is not incremente d, c remains 1
c=1;
4th iteration: i=4;i
here i is incremente d i.e. i value for next iteration is 5
now if(n%i==0) then c is incremente d
i.e. if(5%4==0) then c is incremente d, but 5%4!=0 and so c is not incremente d, c remains 1
c=1;
5th iteration: i=5;i
here i is incremente d i.e. i value for next iteration is 6
now if(n%i==0) then c is incremente d
i.e. if(5%5==0) then c is incremente d, 5%5=0 and so c is incremente d.
i.e. c=2
6th iteration: i=6;i
here i value is 6 and 6
now if(c==2) then n is a prime number
we have c=2 from the 5th iteration and thus n=5 is a Prime number.

Share this games :

1 comments:

Post a Comment

Related Posts