Fill your College Details

Summarise With AI
ChatGPT
Perplexity
Claude
Gemini
Grok
ChatGPT
Perplexity
Claude
Gemini
Grok
Back

C Program To Print Prime Numbers From 1 to n

27 Oct 2025
6 min read

Ever stop to think how your computer decides whether a number is prime or not? That simple “yes” or “no” comes from one of the most fundamental problem-solving exercises in programming, identifying prime numbers.

For beginners, writing a C program to print prime numbers from 1 to n is more than just a math task. This is where you begin to draw the connections between loops, conditions, and logic - the very building blocks of coding. Once you enjoy mastery of this small concept, you will have a stronger and stronger foundation to lean on for every future program you create. 

In this blog, you’ll explore what prime numbers are, how to implement them in C using both for and while loops, and the step-by-step logic behind it, helping you approach coding problems with clarity and confidence.

What You’ll Learn in This Blog

Short on time? Here’s your complete snapshot before you dive in:

  • Understand what prime numbers really are, not just mathematically, but from a programming point of view. Learn how this simple concept plays a key role in logic-building, algorithms, and even cybersecurity.
  • Master the algorithm behind finding and printing prime numbers efficiently. You’ll understand how to use loops and conditions, the heart of any C program.
  • Explore two complete C programs, one using a for loop and another with a while loop, so you can understand both styles of solving the same problem and know when to use which.
  • Get a detailed explanation of each code segment. We’ll break down every line so you know why it’s written that way and how it works behind the scenes.
  • See actual examples and outputs to connect theory with real results. This helps you visualize how the logic executes from start to finish.
  • Learn optimization tips and coding best practices. You’ll see how to write cleaner, faster, and more efficient code habits that every good programmer develops early.
  • End with FAQs that clear common beginner doubts, like “Why is 1 not a prime number?” or “How do I check large numbers efficiently?”

By the end of this blog, you won’t just memorize a program; you’ll understand it deeply. You will be able to write, explain, and even tweak a prime number program in C confidently, a small but powerful step toward becoming a logical thinker and capable programmer.

🎯 Calculate your GPA instantly — No formulas needed!!

Explanation of Prime Numbers

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 influenced evenly or exactly without a remainder by itself and one. If a number has more than 2 factors, then that number is called composite. 

For example, 5 is a prime number because only 1 or 5 divides it. Similarly, 6 is not prime because it can be evenly divided by 1, 2, and 3.  

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 will be odd. 
  3. There are infinitely many primes.
  4.  Prime numbers are important in mathematics, especially in number theory and in the field of 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). For example, 12 can be expressed as 2 x 2 x 3, and the prime factors are 2 and 3. 

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

Basic rules followed by prime numbers

Here are a few basic rules as they pertain to programming:

  • Divisibility Rule: A prime number is only divisible by 1 and itself.
  • Greater Than 1: Prime numbers must be greater than 1.
  • No Negative or Decimal Values: Prime numbers are always positive whole numbers.
  • Unique Prime Factors: Every number greater than 1 can uniquely be expressed as a product of prime factors (this is particularly important if you are coding for factorization).
  • Number 1 is Not Prime: By definition, 1 is not a prime number because it has only one divisor.

Algorithm to print prime numbers from 1 to n in C:

Here is the algorithm to print prime numbers between 1 and n in C:

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:

  •  If temp=0, then the number is divisible only by 1 and itself. Return "num IS PRIME". 
  • Else, if temp>0, then num has divisors other than 1 and itself. Return "num IS NOT PRIME".

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

Thinking about the logic of a program, as shown in a flow chart, it breaks each step into the components of how to tell and show the program is 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.

Flowchart Description

Below is a visual walkthrough of the flowchart of the C program that prints prime numbers from 1 to n:

custom img

Now let’s look at the code for the same:

#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 it. 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.

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

Here’s an example program that prints all prime numbers from 1 to 200.

#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:

First, the program will present a sequence of ten primes, which means that it will be executed 10 times in order to check 10 different numbers. For any number, the program will check whether it is prime or not using a nested for-loop checking divisibility by 2 through half of the number being evaluated at that point in time. If there aren't any divisors for that number, then it will print 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

Here’s the code to print prime numbers from 1 to n using a for loop:

#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, but does not constrain the limit of n to 100. For this program, we are coding to find and print 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, of course, has to skip the number one as that is not a prime number.

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

Here is the code to print prime numbers from 1 to n in C using a while loop:

#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, we will find and use a while loop to print prime numbers from one to n. It has an outer while loop to find 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.

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

Primes can be viewed as special numbers in this exercise; however, writing a C program that tests prime numbers is not just a beginner coding exercise, but a point of transition as to how you will start to understand how to “think” like a programmer going forward.

You not only learned how to print prime numbers, but you also learned about how logic, loops, and conditions come together to create a "thinking" computer. The two solutions we have demonstrated, one to a specific range (1–100) 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 Summary of the Blog

  • Prime numbers are positive integers that are larger than 1 and have no divisors other than 1 and themselves. Recognizing and working with primes is a foundational skill in programming and mathematics.
  • When checking if a number is prime, it’s best practice to test divisibility only up to half of the number or, for greater efficiency, up to the square root of the number. This reduces unnecessary computations and speeds up your program.
  • Both for and while loops can be used to implement prime number checks. Choosing the right loop structure depends on the problem requirements and can help improve code readability and efficiency.
  • Writing programs that allow the user to define the upper limit (n) makes your code more flexible and adaptable for different scenarios, rather than hardcoding a fixed range.
  • Constants: As a reminder, never include one in the list of prime numbers. Prime numbers, simply put, are all numbers greater than 1 that have only two divisors, 1 and themselves. Therefore, one is excluded. 
  • Implementing this program helps strengthen logical thinking, mastery of loops and conditionals, and understanding of basic number theory, skills that are valuable for more advanced programming tasks.
  • Further optimization is possible by skipping even numbers (except 2) when checking for primes, or by wrapping the prime-checking logic in a reusable function for cleaner, modular code.

These key points will help reinforce the most important lessons from your article and provide readers with a concise summary of best practices and concepts learned.

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, you can also consider enrolling in the CCBP Academy 4.0 program so you can 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 (o for efficiency) can be done to reduce 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 loops differ from loops in prime number programs?

While loops are used when the number of iterations is not predetermined, this is because they continue running as long as a condition is true; for loops can be used when you have a fixed number of iterations.

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

Carrying out the programming tasks outlined here helps support logical thinking, continuity with loops and conditionals, and basic electromagnetic theory, which will help you with more advanced programming exercises in the future.

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.

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.

Read More Articles

Chat with us
Chat with us
Talk to career expert