» » » 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:


prime or not in c program


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

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu