For working professionals
For fresh graduates
More
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
Working with numbers is one of the core skills in programming. One of the most common exercises you’ll come across is writing a prime number program in C. This tutorial will walk you through multiple ways to implement prime number logic using loops, functions, recursion, and even optimized algorithms like the Sieve of Eratosthenes.
In this article, we’ll cover different C programs to check for prime numbers, display them in a range, and handle unique scenarios like checking if a number is both prime and Armstrong, or if it can be expressed as a sum of two prime numbers. We’ll explore programs using for loops, while loops, recursion, and functions. By the end, you’ll know not only how to write these programs but also how to pick the right approach for each situation.
Explore our in-depth Software engineering courses to get a broader perspective.
But before moving forward, you must have an understanding of loops and functions in C. So, here’s a quick recap.
In C programming, loops are used to repeat a block of code until a condition is met. The two most commonly used loops are:
Functions help organize your code by putting reusable logic into separate blocks. You can define your own function, call it with arguments, and even return results. This makes programs cleaner and easier to debug.
Unlock your potential with online DBA programs or enroll in the first-of-its-kind Generative AI Doctorate program from Golden Gate University!
A prime number has only two factors: 1 and itself. It must be greater than 1. For example, 2, 3, 5, and 7 are prime numbers. They cannot be divided evenly by any number except 1 and themselves.
Here is the c program to check whether a number is prime or not:
#include <stdio.h>
int main() {
int num, i, isPrime = 1;
// Ask the user to enter a number
printf("Enter a positive integer: ");
scanf("%d", &num);
// 0 and 1 are not prime numbers
if (num <= 1) {
isPrime = 0;
} else {
// Check for factors from 2 to sqrt(num)
for (i = 2; i * i <= num; i++) {
if (num % i == 0) {
// If divisible, then not a prime number
isPrime = 0;
break;
}
}
}
// Output the result
if (isPrime)
printf("%d is a prime number.\n", num);
else
printf("%d is not a prime number.\n", num);
return 0;
}
Sample Output:
Enter a positive integer: 12
12 is not a prime number.
Note: You need to enter a number.
Explanation:
Also Explore: 7 Different Methods to Check Prime Numbers in Python
You can use different methods to write a prime number program in C. You can do it by either:
Let’s explore each of them in detail.
Here’s the code to write prime number program in C using for loop:
#include <stdio.h>
int main() {
int num, i, isPrime = 1;
// Ask the user to enter a number
printf("Enter a positive integer: ");
scanf("%d", &num);
// 0 and 1 are not prime numbers
if (num <= 1) {
isPrime = 0;
} else {
// Check for factors from 2 to sqrt(num)
for (i = 2; i * i <= num; i++) {
if (num % i == 0) {
// If divisible, then not a prime number
isPrime = 0;
break;
}
}
}
// Output the result
if (isPrime)
printf("%d is a prime number.\n", num);
else
printf("%d is not a prime number.\n", num);
return 0;
}
Sample Output:
Enter a positive integer: 7
7 is a prime number.
Explanation:
Here’s the c program to check whether a number is prime or not using while loop:
#include <stdio.h>
int main() {
int num, i = 2, isPrime = 1;
// Ask the user to enter a number
printf("Enter a positive integer: ");
scanf("%d", &num);
// 0 and 1 are not prime numbers
if (num <= 1) {
isPrime = 0;
} else {
// Check for factors using a while loop
while (i * i <= num) {
if (num % i == 0) {
// If divisible, then not a prime number
isPrime = 0;
break;
}
i++;
}
}
// Output the result
if (isPrime)
printf("%d is a prime number.\n", num);
else
printf("%d is not a prime number.\n", num);
return 0;
}
Sample Output:
Enter a positive integer: 5
5 is a prime number.
Explanation:
Must Explore: Prime Number Program in Java
Here’s the prime number program in C to check whether a number is prime or not using recursions:
#include <stdio.h>
// Function to check prime number using recursion
int checkPrime(int num, int i) {
// Base case: if i reaches sqrt(num), number is prime
if (i * i > num) {
return 1; // Prime
}
if (num % i == 0) {
return 0; // Not prime
}
// Recursive call with next value of i
return checkPrime(num, i + 1);
}
int main() {
int num;
// Ask the user to enter a number
printf("Enter a positive integer: ");
scanf("%d", &num);
// Base case for 0 and 1
if (num <= 1) {
printf("%d is not a prime number.\n", num);
} else {
// Call the recursive function
if (checkPrime(num, 2)) {
printf("%d is a prime number.\n", num);
} else {
printf("%d is not a prime number.\n", num);
}
}
return 0;
}
Sample Output:
Enter a positive integer: 3
3 is a prime number.
Explanation:
Must Explore: Introduction to C Tutorial
Here’s the prime number program in C to check whether a number is prime or not using functions:
#include <stdio.h>
// Function to check prime number using recursion
int checkPrime(int num, int i) {
// Base case: if i reaches sqrt(num), number is prime
if (i * i > num) {
return 1; // Prime
}
if (num % i == 0) {
return 0; // Not prime
}
// Recursive call with next value of i
return checkPrime(num, i + 1);
}
int main() {
int num;
// Ask the user to enter a number
printf("Enter a positive integer: ");
scanf("%d", &num);
// Base case for 0 and 1
if (num <= 1) {
printf("%d is not a prime number.\n", num);
} else {
// Call the recursive function
if (checkPrime(num, 2)) {
printf("%d is a prime number.\n", num);
} else {
printf("%d is not a prime number.\n", num);
}
}
return 0;
}
Sample Output:
Enter a positive integer: 29
29 is a prime number.
Explanation:
Must Read: 29 C Programming Projects in 2025 for All Levels [Source Code Included]
This program prints all prime numbers between two given numbers using a simple loop and condition checks. Here’s the code:
#include <stdio.h>
int main() {
int start, end, i, j, isPrime;
// Ask the user for the range
printf("Enter the start and end values: ");
scanf("%d %d", &start, &end);
printf("Prime numbers between %d and %d are:\n", start, end);
// Loop through each number in the range
for (i = start; i <= end; i++) {
if (i <= 1) continue; // Skip 0 and 1
isPrime = 1;
// Check if i is divisible by any number from 2 to sqrt(i)
for (j = 2; j * j <= i; j++) {
if (i % j == 0) {
isPrime = 0;
break;
}
}
// If prime, print it
if (isPrime)
printf("%d ", i);
}
return 0;
}
Sample Output:
Enter the start and end values: 10 30Prime numbers between 10 and 30 are: 11 13 17 19 23 29
Explanation:
We move the prime-checking logic into a function to make the code clean and reusable. Here’s the code:
#include <stdio.h>
// Function to check if a number is prime
int isPrime(int num) {
int i;
if (num <= 1) return 0;
for (i = 2; i * i <= num; i++) {
if (num % i == 0)
return 0;
}
return 1;
}
int main() {
int start, end, i;
// Ask the user for the range
printf("Enter the start and end values: ");
scanf("%d %d", &start, &end);
printf("Prime numbers between %d and %d are:\n", start, end);
for (i = start; i <= end; i++) {
if (isPrime(i))
printf("%d ", i);
}
return 0;
}
Sample Output:
Enter the start and end values: 5 15Prime numbers between 5 and 15 are: 5 7 11 13
Explanation:
This is a fast method to find all prime numbers up to a large number. Here’s the code:
#include <stdio.h>
#include <stdbool.h>
int main() {
int start, end, i, j;
// Ask the user for the range
printf("Enter the start and end values: ");
scanf("%d %d", &start, &end);
// Boolean array to mark prime numbers
bool isPrime[end + 1];
// Assume all numbers are prime initially
for (i = 0; i <= end; i++) {
isPrime[i] = true;
}
// Sieve algorithm
isPrime[0] = isPrime[1] = false;
for (i = 2; i * i <= end; i++) {
if (isPrime[i]) {
for (j = i * i; j <= end; j += i) {
isPrime[j] = false;
}
}
}
// Print primes in the given range
printf("Prime numbers between %d and %d are:\n", start, end);
for (i = start; i <= end; i++) {
if (isPrime[i])
printf("%d ", i);
}
return 0;
}
Sample Output:
Enter the start and end values: 1 50Prime numbers between 1 and 50 are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Explanation:
Also Explore: Compilation process in C
This method asks the user to define any custom range and prints the primes using a for loop. Here’s the code:
#include <stdio.h>
int main() {
int lower, upper, i, j, isPrime;
// Get the user-defined range
printf("Enter the lower and upper limits: ");
scanf("%d %d", &lower, &upper);
printf("Prime numbers between %d and %d are:\n", lower, upper);
for (i = lower; i <= upper; i++) {
if (i <= 1) continue;
isPrime = 1;
for (j = 2; j * j <= i; j++) {
if (i % j == 0) {
isPrime = 0;
break;
}
}
if (isPrime)
printf("%d ", i);
}
return 0;
}
Sample Output:
Enter the lower and upper limits: 20 40Prime numbers between 20 and 40 are: 23 29 31 37
Explanation:
This program checks whether a number is prime, Armstrong, or both. A number is:
Here’s the code:
#include <stdio.h>
#include <math.h>
// Function to check if a number is prime
int isPrime(int num) {
if (num <= 1) return 0;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0)
return 0;
}
return 1;
}
// Function to check if a number is Armstrong
int isArmstrong(int num) {
int original = num, sum = 0, digit;
int n = 0;
// Count the number of digits
int temp = num;
while (temp != 0) {
n++;
temp /= 10;
}
// Calculate the sum of digits raised to power n
temp = num;
while (temp != 0) {
digit = temp % 10;
sum += pow(digit, n);
temp /= 10;
}
return (sum == original);
}
int main() {
int number;
// Ask the user for input
printf("Enter a number: ");
scanf("%d", &number);
// Check and display the results
if (isPrime(number))
printf("%d is a Prime Number.\n", number);
else
printf("%d is NOT a Prime Number.\n", number);
if (isArmstrong(number))
printf("%d is an Armstrong Number.\n", number);
else
printf("%d is NOT an Armstrong Number.\n", number);
return 0;
}
Sample Output:
Enter a number: 153153 is NOT a Prime Number.153 is an Armstrong Number.
Explanation:
We use two functions:
You can now check both conditions in one program, helping in numerical puzzles or quizzes.
For more information, check out the Armstrong Number in C article!
This program checks whether a number can be split into the sum of two prime numbers. This is often asked in the context of Goldbach's Conjecture, which says: Every even number greater than 2 can be expressed as the sum of two primes." Here’s the code:
#include <stdio.h>
// Function to check if a number is prime
int isPrime(int num) {
if (num <= 1) return 0;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0)
return 0;
}
return 1;
}
int main() {
int num, i, found = 0;
// Ask the user for a number
printf("Enter a number: ");
scanf("%d", &num);
// Check all pairs (i, num-i) to see if both are prime
for (i = 2; i <= num / 2; i++) {
if (isPrime(i) && isPrime(num - i)) {
printf("%d = %d + %d\n", num, i, num - i);
found = 1;
}
}
if (!found)
printf("The number %d cannot be expressed as the sum of two prime numbers.\n", num);
return 0;
}
Output:
Enter a number: 3434 = 3 + 3134 = 5 + 2934 = 11 + 2334 = 17 + 17
Explanation:
Here are some of the best practices to follow:
Learning how to write a prime number program in C helps build strong logic skills. You explored different ways to check for prime numbers using loops, recursion, and functions. Each method has its use depending on the problem.
Whether it's checking a single number or a range, these examples will help you write clean, efficient C programs. With regular practice, you can solve more complex number-related problems confidently.
A prime number is a positive integer greater than 1 that has no positive divisors other than 1 and itself. For example, 2, 3, 5, and 7 are prime numbers.
A prime number is a natural number greater than 1 that is divisible only by 1 and itself. In C, we use conditional logic and loops to check if any other divisor exists between 2 and the square root of the number.
You can write a prime number checker in C using various techniques such as loops, recursion, or modular functions. Each method has its benefits depending on code clarity, reusability, and the size of the number range.
To check if a number is prime, we check if it is divisible by any number from 2 to the square root of the number. If it is divisible, the number is not prime; otherwise, it is prime.
There are several methods to check for prime numbers in C:
Both loops can be used to iterate through potential divisors. A for loop is better when the iteration count is fixed, while a while loop offers more flexibility if the condition depends on runtime logic or dynamic inputs.
Both loops work similarly, but the for loop is ideal when the number of iterations is known, whereas the while loop is useful when the loop continues until a specific condition is met.
Recursion simplifies the logic by checking one divisor at a time, calling the same function repeatedly. If a divisor is found, it stops and returns false. If it reaches the square root without finding one, it returns true.
In recursion, a function calls itself with the next integer until it finds a divisor or reaches the square root of the number. If no divisor is found, the number is prime.
The Sieve of Eratosthenes is an efficient algorithm to find all prime numbers up to a given limit. It works by marking the non-prime numbers in a range, leaving only the primes.
Yes, a number can be both prime and Armstrong, though this is rare. Prime numbers have specific divisibility rules, while Armstrong numbers follow digit-based power sum logic. The checks for both are performed using separate code blocks in C.
Functions improve code readability, reusability, and debugging. You can isolate the prime-checking logic into a separate function and call it multiple times with different inputs, making the code cleaner and more modular.
Functions help modularize the code, making it reusable and easier to debug. A function to check if a number is prime can be reused multiple times without rewriting the logic each time.
To display prime numbers in a range, loop through each number in the range and check if it is prime. If it is, print it.
The time complexity of checking whether a number is prime using the method that checks divisibility up to the square root of the number is O(n)O(\sqrt{n})O(n).
You can write a loop from the starting number to the ending number, checking each for primality using a function or direct logic. If the number passes the check, you print it as part of the result.
Any factor larger than the square root would have a corresponding factor smaller than it. So if no divisor exists up to the square root, the number is guaranteed to be prime, making the check both accurate and efficient.
If a number has a divisor larger than its square root, the corresponding smaller divisor must already have been checked. Thus, checking divisibility only up to the square root is more efficient.
The program will output whether the entered number is prime or not based on the checks applied. If the number is prime, the output will state that it is prime; otherwise, it will indicate it is not.
Yes, the program can check prime numbers for any valid integer input. However, the efficiency may decrease for very large numbers, and more optimized algorithms like the Sieve of Eratosthenes should be used for larger ranges.
The Sieve of Eratosthenes marks multiples of prime numbers as non-prime, which significantly reduces the number of checks required for large ranges, improving performance compared to checking each number individually.
Yes, the same program can check large numbers, but performance may slow down with basic logic. For better speed, especially when working with ranges or big numbers, use optimized algorithms like the Sieve of Eratosthenes.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.