Print Prime Numbers from 1 to 100 Using For Loop


Explanation

A for loop can be used to print all prime numbers from 1 to 100. A prime number is a number that has exactly two factors: 1 and itself. In this program, the outer for loop checks every number from 2 to 100. The inner for loop counts how many times the current number is exactly divisible. If the count is equal to 2, the number is a prime number and is displayed on the screen.

How It Works?

  • Step 1: Declare the variables i, j, and count.
  • Step 2: Use the outer for loop to check numbers from 2 to 100.
  • Step 3: Set count = 0 before checking each number.
  • Step 4: Use the inner for loop to divide the current number by every value from 1 to the number itself.
  • Step 5: If the remainder is 0, increase count by 1.
  • Step 6: After checking all divisors, test whether count == 2.
  • Step 7: If the condition is true, print the number because it is a prime number.
  • Step 8: Continue until all numbers from 1 to 100 have been checked.

Example Program


#include <stdio.h>
#include <conio.h>

main()
{

    int i, j, count;

    clrscr();

    printf("Prime Numbers from 1 to 100:\n\n");

    for(i = 2; i <= 100; i = i + 1)
    {

        count = 0;

        for(j = 1; j <= i; j = j + 1)
        {

            if(i % j == 0)
            {

                count = count + 1;

            }

        }

        if(count == 2)
        {

            printf("%d\t", i);

        }

    }

    getch();

}

Output

Prime Numbers from 1 to 100:

2   3   5   7   11   13   17   19   23   29
31   37   41   43   47   53   59   61   67   71
73   79   83   89   97

Practice Exercises

Task 1: Write a C program using the for loop to print all prime numbers from 1 to 50.

Goal: Learn how to use nested for loops and the if statement to check whether a number is prime and display all prime numbers within a given range.

💡 Hint: Use an outer for loop from 2 to 50. For each number, use another for loop to count its factors. If the count is equal to 2, print the number.
💡 Show Solution

#include <stdio.h>
#include <conio.h>

main()
{

    int i, j, count;

    clrscr();

    printf("Prime Numbers from 1 to 50:\n\n");

    for(i = 2; i <= 50; i = i + 1)
    {

        count = 0;

        for(j = 1; j <= i; j = j + 1)
        {

            if(i % j == 0)
            {

                count = count + 1;

            }

        }

        if(count == 2)
        {

            printf("%d\t", i);

        }

    }

    getch();

}

Output
Prime Numbers from 1 to 50:

2   3   5   7   11   13   17   19   23   29
31   37   41   43   47
Explanation: The program uses two for loops. The outer loop checks each number from 2 to 50. The inner loop counts how many numbers divide the current number exactly. If the count is equal to 2, the number has only two factors (1 and itself), so it is printed as a prime number.