» » » Prime number program in c using for loop and while loop

# Prime number program in c using for loop and while loop

• Any number which is divisible by 1 and itself is known as prime number.
• To check prime number or not in c programming we need to use for loop and iterate from 2 to half of the number.
• If any number is divisible then it is non prime number, we can exit the loop.
• Let us see an example program on c to check a number is prime number or not
• prime number program in c using for loop

Program #1:  Write a c program to check a number is prime number or not using for loop.

1. #include <stdio.h>
2. int main()
3. {
4.
5.    int n, i, count = 0;
6.
7.     printf("Enter number to check prime number or not");
8.     scanf("%d",&n);
9.
10.     for(i=2; i<=n/2; ++i)
11.     {
12.         // check for non prime number
13.         if(n%i==0)
14.         {
15.             count=1;
16.             break;
17.         }
18.     }
19.
20.     if (count==0)
21.         printf("%d is a prime number.",n);
22.     else
23.         printf("%d is not a prime number.",n);
24.
25.     getch();
26. }

Output:

Program #2:  Write a c program to check a number is prime number or not using while loop.

1. #include <stdio.h>
2. int main()
3. {
4.    int n, i, count = 0;
5.
6.     printf("Enter number to check prime number or not");
7.     scanf("%d",&n);
8.     i=2;
9.     while( i<=n/2)
10.     {
11.         // check for non prime number
12.         if(n%i==0)
13.         {
14.             count=1;
15.             break;
16.         }
17.         i++;
18.     }
19.
20.     if (count==0)
21.         printf("%d is a prime number.",n);
22.     else
23.         printf("%d is not a prime number.",n);
24.
25.     getch();
26.
27. }

Output:

1. Enter number to check prime number or not
2. 12
3. 12 is not a prime number

#### Instance Of Java

1. 