Prime Number Program in C using For loop and While loop

Prime Number: A number that is divisible only by itself and 1 is called Prime number.
Examples: 2, 3, 5, 7, 11, 13, 17, 19 etc.
Prime number programs in c:
Program to display the prime numbers from 1 to 100:
#include<stdio.h>
 int main()
 {
  int limit = 100;
  printf("Prime numbers between 1 and 100");
      for(int i=2; i < limit; i++)
     {
       int flag = 0;
       for(int j=2; j < i ; j++)
        {
         if(i % j == 0)
         {
            flag = 1;
            break;
          }
         }
     if(flag == 0)
    printf("%d ", i);
  }
}


Output: Prime numbers between 1 and 1002 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

Program to display prime numbers from 1 to n:

#include<stdio.h>
int main()
{
 int n;
 printf("Enter the value of N");
 scanf("%d", &n);
    for(int i=2; i < n; i++)
     {
      int flag = 0;
       for(int j=2; j < i ; j++)
        {
         if(i % j == 0)
         {
           flag = 1;
            break;
          }
         }
     if(flag == 0)
    printf("%d ", i);
   }
}

 


output:
Enter the value of N 50                                                                                                               
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

Prime number using while loop:
#include<stdio.h>
int main()
 {
 int n,i = 2,flag;
 printf("Enter the value of N");
 scanf("%d", &n);
 flag = 0;
 while(i <= n/2)
 {
  if(n % i == 0)
  {
   flag = 1;
   break;
  }
 i++;
 }
 if(flag == 0)
        printf("Prime Number");
    else
        printf("Not Prime Number");
    return 0;
}


Enter the value of N 10                                                                                                               
Not Prime Number 

Share:

Search This Blog

  • ()

Our Services

Powered by Blogger.

Netflix codes - Find all secret Netflix codes that unlock tons of hidden movies.

Netflix codes - Find all secret Netflix codes that unlock tons of hidden movies. As all Netflix clients know, the gushing admin...