View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Introduction to Prime Number Program in C

Updated on 16/04/20252,463 Views

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.

How Loops and Functions Work in C?

In C programming, loops are used to repeat a block of code until a condition is met. The two most commonly used loops are:

  • for loop: Best when the number of iterations is known.
  • while loop: Useful when the loop continues until a certain condition is true.

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!

C Program to Check Whether a Number is Prime or Not

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:

  • The program takes an integer input from the user.
  • It first checks if the number is less than or equal to 1. If yes, it's not prime.
  • Then it checks for factors from 2 to sqrt(num) using i * i <= num.
    • If any number divides num exactly, it's not prime.
    • If no divisors are found, it's prime.

Also Explore: 7 Different Methods to Check Prime Numbers in Python

Different Methods to Write a Prime Number Program in C to Check Whether a Number is Prime or Not 

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.

Prime Number Program in C to Check Whether a Number is Prime or Not Using for Loop

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:

  • The program asks for a number and checks if it’s prime using a for loop.
  • It runs a loop from 2 to sqrt(num) and checks if the number is divisible by any of the loop values.
  • If any number divides it exactly, it's not prime; otherwise, it's prime.

Prime Number Program in C to Check Whether a Number is Prime or Not Using while Loop

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:

  • Similar to the for loop method, but here we use a while loop.
  • The loop runs as long as i * i <= num, checking divisibility.
  • If no divisor is found, the number is prime.

Must Explore: Prime Number Program in Java

Prime Number Program in C to Check Whether a Number is Prime or Not Using Recursions

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:

  • This method uses recursion to check for prime numbers.
  • The function checkPrime() checks divisibility starting from i = 2, and it recurses until i * i > num.
  • If a divisor is found, it returns 0, indicating the number is not prime.

Must Explore: Introduction to C Tutorial

Prime Number Program in C to Check Whether a Number is Prime or Not Using Functions

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:

  • The program defines a function isPrime() that checks for prime numbers.
  • It takes a number as an argument and checks for factors from 2 to sqrt(num).
  • If no divisors are found, it returns 1, meaning the number is prime.

Must Read: 29 C Programming Projects in 2025 for All Levels [Source Code Included]

C Program to Display Prime Numbers Between Two Intervals

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:

  • The loop checks each number in the given range.
  • If a number is not divisible by any number other than 1 and itself, it is printed.

C Program to Display Prime Numbers in a Range Using a Function 

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:

  • The isPrime() function checks if a number is prime.
  • The main function calls this for each number in the range.

C Program to Find Prime Number Using the Sieve of Eratosthenes Algorithm

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:

  • The Sieve of Eratosthenes marks all non-prime numbers in a range.
  • It’s very fast for larger intervals.

Also Explore: Compilation process in C

C Program to Check Prime Numbers Within a User-defined Range

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 is similar to the earlier loop-based method.
  • The program asks the user for the lower and upper limit and checks for primes in that interval.

C Program to Check if a Number is Prime or Armstrong

This program checks whether a number is prime, Armstrong, or both. A number is:

  • Prime if it is only divisible by 1 and itself.
  • Armstrong if the sum of the cubes of its digits equals the number itself (for 3-digit numbers).

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:

  • isPrime() checks if a number is divisible by any number from 2 to sqrt(n).
  • isArmstrong() calculates the power sum of digits and compares it with the original number.

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!

Program to Check if a Number Can Be Expressed as the Sum of Two Prime Numbers

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:

  • The program checks each number i from 2 to num/2.
  • For each i, it checks if both i and num - i are prime.
  • If they are, it prints the combination.
  • This is useful for understanding prime pair decomposition.

Best Practices for Implementing Prime Number Programs in C

Here are some of the best practices to follow:

  • Use a loop that runs up to the square root of the number for efficiency.
  • Skip checking even numbers after verifying 2 to reduce unnecessary checks.
  • Exit the loop as soon as a factor is found to save time.
  • Encapsulate prime checking logic in a reusable function like isPrime().
  • Use clear and descriptive variable names like start, end, num, flag.
  • Keep variables within the smallest possible scope to improve clarity.
  • Validate user input to avoid negative numbers or invalid types.
  • Add inline comments to explain why a certain check or loop is used.
  • Maintain consistent code formatting for readability.
  • Prefer int for general use, but use long long for larger ranges.
  • Avoid recalculating values like sqrt(num) repeatedly inside loops.
  • Use the Sieve of Eratosthenes when generating many primes in a range.
  • Allocate memory dynamically if working with large ranges in the Sieve.
  • Print meaningful output messages that guide the user clearly.
  • For problems like expressing a number as the sum of two primes, check all valid pairs.

Conclusion

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.

FAQs

1. What is a prime number in C?

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.

2. What is the concept of a prime number and how is it implemented in C programming?

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.

3. What are the different approaches to writing a prime number checker in C language?

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.

4. How do we check if a number is prime in C?

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.

5. What are the different methods to check if a number is prime in C?

There are several methods to check for prime numbers in C:

  • Using a for loop
  • Using a while loop
  • Using recursion
  • Using functions for modularity

6. How do for loops and while loops compare when used in a prime number program?

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.

7. What is the difference between using a for loop and a while loop for checking prime numbers?

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.

8. How does a recursive function help in checking whether a number is prime?

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.

9. How does recursion work in a prime number program?

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.

10. What is the Sieve of Eratosthenes algorithm?

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.

11. Can a number be both prime and Armstrong in C programs?

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.

12. Why should you use functions to check prime numbers in C instead of writing all logic in main()

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.

13. What is the role of functions in checking prime numbers in C?

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.

14. How do you display prime numbers within a range in C?

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.

15. What is the time complexity of checking prime numbers?

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​).

16. How can you print all prime numbers in a specific range using a C program?

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.

17. Why do C programs check divisibility only up to the square root for prime checks?

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.

18. Why is the square root used when checking for prime numbers?

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.

19. What is the output of the prime number program?

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.

20. Can this program be used to check prime numbers larger than 100?

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.

21. How does the Sieve of Eratosthenes improve the prime-checking process?

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.

22. Can the same program be used to check large numbers like 1000 or 10,000?

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.

image

Take a Free C Programming Quiz

Answer quick questions and assess your C programming knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

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.