Prime Numbers From 1 To N C Program

By | August 6, 2016

C Program To Print Prime Numbers from 1 To N

Learn How To Print Prime Numbers from 1 To N in C Programming Language. We have mentioned two methods below that focuses on While Loop and For Loop. You can alter this program to Display Prime Integers from 1 To 100.

Also Read: C Program To Check if a Number is Prime or Not

Method 1: C Program To Print Prime Numbers from 1 To N using For Loop

#include <stdio.h>

int main()
{
      int limit, num, count, temp;
      printf("Enter the Limit:\t");
      scanf("%d", &limit);
      for(num = 2; num <= limit; num++)
      {
            for(count = 2; count < num; count++)
            {
                  if(num % count == 0)
                  {
                        temp = 0;
                        break;
                  }
                  temp = 1;
            }
            if(temp == 1)
            {
                  printf("\n%d is a Prime Number", num);
            }
            else if(temp == 0)
            {
                  printf("\n%d is Not a Prime Number", num);
            }
      }
      printf("\n");
      return 0;
}

Method 2: C Program To Print Prime Numbers from 1 To 100 using While Loop

#include <stdio.h>

int main()
{
      int limit, num = 2, temp;
      printf("Enter the Limit:\t");
      scanf("%d", &limit);
      while(num <= limit)
      {
            int count = 2;
            while(count < num)
            {
                  if(num % count == 0)
                  {
                        temp = 0;
                        break;
                  }
                  temp = 1;
                  count++;
            }
            if(temp == 1)
            {
                  printf("\n%d is a Prime Number", num);
            }
            else if(temp == 0)
            {
                  printf("\n%d is Not a Prime Number", num);
            }
            num++;
      }
      printf("\n");
      return 0;
}

Output

C Program To Print Prime Numbers From 1 To N using For Loop

If you have any compilation error or doubts in this C Program To Generate Prime Integers from 1 To N, let us know about it in the Comment Section below.

2 thoughts on “Prime Numbers From 1 To N C Program

  1. Jai bhanushali

    Why do we have to initialize the for loop with 2? Why can’t we use use 0 instead of 2? The output for this Prime Number generation C Program is correct, but I am still confused.

    Reply
    1. Tushar Soni Post author

      Jai, 2 is the smallest Prime Number. Hence, we start the loop with 2. Try starting it with 0 or 1. You will see the difference in the output.

      Reply

Let's Discuss