C Program To Print Prime Numbers From 1 to n

Published: 27 Oct 2025
Reading Time: 6 min read

Table of Contents

Introduction

Writing a C program to print prime numbers from 1 to n is a fundamental problem-solving exercise in programming. For beginners, this task helps develop understanding of loops, conditions, and logic - the building blocks of coding. This tutorial explores what prime numbers are, how to implement them in C using both for and while loops, and the step-by-step logic behind the implementation.

What You'll Learn in This Blog

This comprehensive guide covers:

By the end of this tutorial, you will be able to write, explain, and modify a prime number program in C confidently.

Explanation of Prime Numbers

Definition

A prime number is a natural number that is greater than one and has only two positive factors: itself and one. In other words, a prime number is divisible evenly (exactly without a remainder) only by itself and one. If a number has more than 2 factors, then that number is called composite.

Examples:

Key Properties of Prime Numbers

  1. The smallest prime is 2, which is the only even prime. Every other even number is divisible by 2 (itself and 1) and thus cannot be prime.
  2. All primes after 2 are odd numbers
  3. There are infinitely many primes
  4. Prime numbers are important in mathematics, especially in number theory and cryptography

Why Prime Numbers Matter

Prime numbers are called the building blocks of natural numbers since every number greater than 1 can be expressed as the product of prime numbers (called the Fundamental Theorem of Arithmetic).

Example: 12 can be expressed as 2 × 2 × 3, where the prime factors are 2 and 3.

Understanding what makes a number prime is important before learning how to identify primes or writing programs to identify them.

Basic Rules for Prime Numbers

Key rules for programming:

Algorithm to Print Prime Numbers from 1 to n in C

Step-by-Step Algorithm

Step 1: Ask for the number num as input

Step 2: Set the variable temp to 0

Step 3: Loop from 2 to num/2 with a for loop

Step 4: Inside the loop, check if num is divisible by the current iterator value. If it is, increment temp by 1

Step 5: When the loop finishes, check the variable temp:

Flowchart for C Program to Print Prime Numbers from 1 to n

A flowchart breaks down each step of the logic for finding and printing all prime numbers from 1 to n. Flowcharts are especially helpful for beginners, as they provide a clear, step-by-step map of the decision-making and looping processes involved.

The flowchart provides a visual walkthrough of the C program that prints prime numbers from 1 to n, showing the decision-making and looping processes.

Basic Implementation Code

#include <stdio.h>

int main() {
    int i, num, n, count;

    // Take input for the range
    printf("Enter the range: ");
    scanf("%d", &n);

    // Print the prime numbers in the given range
    printf("The prime numbers between 1 and %d are: ", n);

    for (num = 2; num <= n; num++) { // Start from 2 since 1 is not a prime number
        count = 0; // Reset the count for each number

        for (i = 2; i <= num / 2; i++) { // Check divisors from 2 to num/2
            if (num % i == 0) { // If divisible, it's not a prime number
                count++;
                break; // Exit the loop if a divisor is found
            }
        }

        // If count is still 0, the number is prime
        if (count == 0) {
            printf("%d ", num);
        }
    }

    printf("\n"); // Print a newline for cleaner output

    return 0; // Return 0 to indicate successful execution
}

Explanation

The program accepts a user-provided upper bound, n, and checks each number starting from two to see whether it is prime. A for loop determines whether to use a count variable as a divisor, beginning with the number two and ending at half of the number (num/2). If any of the divisor numbers can divide num evenly, the program can exit and note that it is not a prime number. If none of the divisor numbers made it divisible, it is noted as a prime number and printed. Using the while loop, the program will check each number until reaching n.

In this example, the user simply needs to specify the upper bound of numbers, and the program will print all numbers that are prime between 1 and n.

Sample Output

Enter the range: 50
The prime numbers between 1 and 50 are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

=== Code Execution Successful ===

C Program to Print Prime Numbers From 1 to 200 Using FOR Loop

This example program prints all prime numbers from 1 to 200.

Code Implementation

#include <stdio.h>

int main() {
    int i, num, count;

    printf("The prime numbers between 1 and 200 are: ");

    for(num = 2; num <= 200; num++) { // Loop from 2 to 200
        count = 0;

        // Check divisors from 2 to num/2
        for(i = 2; i <= num / 2; i++) {
            if(num % i == 0) {
                count++;
                break;
            }
        }

        // If no divisors are found, the number is prime
        if(count == 0) {
            printf("%d ", num);
        }
    }

    printf("\n"); // Print newline for cleaner output
    return 0;     // Indicate successful program termination
}

Explanation

The program presents a sequence of prime numbers by executing a loop to check different numbers. For any number, the program checks whether it is prime using a nested for-loop checking divisibility by 2 through half of the number being evaluated. If there aren't any divisors for that number, then it prints that number as prime. The code defaults to skipping one since it is not a prime and uses the variable count to determine the divisibility of each number.

Output

The prime numbers between 1 and 200 are: 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 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199

=== Code Execution Successful ===

C Program to Print Prime Numbers From 1 to n Using FOR Loop

This program prints prime numbers from 1 to n using a for loop, where n is user-defined.

Code Implementation

#include <stdio.h>

int main(void) { // Use int main(void) for standard compliance
    int i, num, n, count;
    printf("Enter the range: ");
    scanf("%d", &n);
    printf("The prime numbers between 1 and %d are: ", n);

    for (num = 2; num <= n; num++) { // Start from 2 as 1 is not a prime number
        count = 0;
        for (i = 2; i <= num / 2; i++) { // Check divisibility up to num/2
            if (num % i == 0) {
                count++;
                break; // Exit the loop if a divisor is found
            }
        }
        if (count == 0) { // If count is still 0, the number is prime
            printf("%d ", num);
        }
    }
    printf("\n");

    return 0; // Return 0 to indicate successful execution
}

Explanation

This program prints out prime numbers from one to n, without constraining the limit of n. The program finds and prints all prime numbers in any range using a for loop. The user enters an upper limit n, and the code checks every number from one to n. For each number, there is a nested for loop that looks for both primes and divisibility of that number by any number that is less than half its size. If there are no divisors found (other than 1) in the nested for loop, the number will be considered a prime number and will be printed. The code skips the number one as that is not a prime number.

Sample Output

Enter the range: 200
The prime numbers between 1 and 200 are: 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 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199

=== Code Execution Successful ===

C Program to Print Prime Numbers From 1 to n Using WHILE Loop

This program demonstrates how to print prime numbers from 1 to n using a while loop instead of a for loop.

Code Implementation

#include <stdio.h>

int main(void) { // Use int main(void) for standard compliance
    int n, num = 2, i, isPrime;

    printf("Enter the range: ");
    scanf("%d", &n);

    printf("The prime numbers between 1 and %d are: ", n);

    while (num <= n) {
        isPrime = 1; // Assume the number is prime
        i = 2;
        while (i <= num / 2) { // Check divisors from 2 to num/2
            if (num % i == 0) {
                isPrime = 0; // Not a prime number
                break;
            }
            i++;
        }
        if (isPrime && num != 1) { // If prime and not 1, print it
            printf("%d ", num);
        }
        num++;
    }

    printf("\n");
    return 0; // Return 0 to indicate successful execution
}

Explanation

In this program, a while loop is used to find and print prime numbers from one to n. It has an outer while loop to check each number starting from two up to n. For each number, an inner while loop checks if it's divisible by any number between 2 and half of itself. If no divisors are found, the number is prime and printed. With the while loop, the program checks each number until reaching the upper limit n.

Sample Output

Enter the range: 50
The prime numbers between 1 and 50 are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

=== Code Execution Successful ===

Conclusion

Writing a C program that tests prime numbers is not just a beginner coding exercise, but a transition point in understanding how to "think" like a programmer. You learned not only how to print prime numbers, but also how logic, loops, and conditions come together to create a "thinking" computer.

The two solutions demonstrated - one for a specific range (1-200) and one user-supplied (1-n) - show that programming in the real world is about establishing a context and then adapting to that context at runtime.

From implementing these programs, you have developed more than syntax knowledge; you have developed the mental discipline to optimize loops, determine conditional logic, and develop solutions based on context. These are the foundational habits exhibited early by every great software engineer.

Key Takeaways and Summary

Core Concepts

Career Development

Mastering basics is necessary to develop programming skills and is vital for a successful career in software companies where adaptability and problem-solving are highly valued. To strengthen your foundations, consider enrolling in the CCBP Academy 4.0 program to be job-ready by the time you finish college.

Frequently Asked Questions

1. What is the purpose of checking divisibility up to num/2 or sqrt(num) in prime number programs?

Checking up to num/2 (or for efficiency, sqrt(num)) reduces unnecessary computations. If a number has a divisor larger than half of itself, it would already have a smaller divisor. So, checking beyond this limit is not needed.

2. How do for loops differ from while loops in prime number programs?

While loops are used when the number of iterations is not predetermined - they continue running as long as a condition is true. For loops are used when you have a fixed number of iterations.

3. Why is the number 1 excluded from being a prime number?

By definition, 1 is not a prime number because it has only one divisor (itself). Prime numbers must have exactly two divisors: 1 and the number itself.

4. How can learning to print prime numbers help in learning programming?

Printing prime numbers teaches you key concepts like loops, conditional statements, and number theory. All of these are used in bigger programs, too. The programming tasks outlined here help support logical thinking, continuity with loops and conditionals, and basic number theory, which will help with more advanced programming exercises in the future.

5. Can the prime number printing program be optimised further?

The program can be optimised by skipping even numbers (except 2) in the prime check, or by wrapping the prime-checking logic in a reusable function for cleaner, modular code.

Related Articles


About NxtWave

NxtWave provides industry-recognized IT certifications and training programs including CCBP Academy 4.0 and NxtWave Intensive courses.

Contact Information: