Published: 27 Oct 2025
Reading Time: 6 min read
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.
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.
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:
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.
Key rules for programming:
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:
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.
#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
}
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.
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 ===
This example program 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
}
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.
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 ===
This program prints prime numbers from 1 to n using a for loop, where n is user-defined.
#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
}
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.
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 ===
This program demonstrates how to print prime numbers from 1 to n using a while loop instead of a for 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
}
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.
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 ===
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.
Prime numbers are positive integers larger than 1 that have no divisors other than 1 and themselves. Recognizing and working with primes is a foundational skill in programming and mathematics.
Optimization technique: When checking if a number is prime, 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.
Loop structures: 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.
Flexible programming: 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.
Important reminder: Never include one in the list of prime numbers. Prime numbers are all numbers greater than 1 that have only two divisors: 1 and themselves. Therefore, one is excluded.
Skill development: 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: 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.
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.
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.
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.
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.
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.
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.
About NxtWave
NxtWave provides industry-recognized IT certifications and training programs including CCBP Academy 4.0 and NxtWave Intensive courses.
Contact Information: