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:

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

11 − 4 =