C Program to Print Prime Numbers From 1 to N

programming

Problem: Write a program in C to print all prime numbers till the given number n.

A Prime number is a number that is only divisible by itself and 1. For example 5.

To print all prime numbers up to n, we have to check each number individually whether it is Prime or not. To do this, we:

  1. Loop from 1 to N (i).
    1. Nest another loop from 2 to less than i (j).
      1. Inside the nested loop, we check if(i%j == 0).
        1. If true then i is not a prime number.
        2. Therefore, break out of the nested loop.
    2. Otherwise, if the iteration loops till the end, then i is a prime number.
      1. Print i.

Note: The value of n should be entered by the user and should be positive.

Here is the implementation of the steps in C:

#include <stdio.h>
#include <stdbool.h>
 
int main()
{
  int n;

  printf("Enter value of n \n");
  scanf("%d",&n);

  printf("Prime Number between 1 to %d are: \n",n);

  //Iterate through all numbers till n
  for(int i=1; i<=n; i++){
    //boolean variable to mark whether i is prime or not
    bool isPrime = true;

    for(int j=2; j<i; j++){
      /*
        *If i is divisble by j then,
        *it means i is not prime
      */
      if(i%j == 0){
        //mark as not prime
        isPrime = false;
        break;
      }
    }

    //If isPrime remains true, then output i because its a prime number
    if(isPrime)
      printf("%d, ",i);
  }

  return 0;
}

Output for All Prime Numbers from 1 to 100:

C Program to Print Prime Numbers From 1 to N

In this programming example, we learned to write a program in C to print all prime number till the given number ‘n’. If you have any doubt then do comment below.

Leave a Reply

Your email address will not be published. Required fields are marked *