Back

Prime Number Program in C: A Comprehensive Guide with Examples

05 Dec 2024
6 min read

A prime number is a natural number greater than one which does not have any divisor other than itself and one. For instance, 2, 3, 5, 7, and 11 are prime numbers. Prime numbers are fundamental in mathematics and computer science, especially in fields like cryptography and number theory.

In programming, a prime number program in C involves writing algorithms to determine whether a number is prime. It can also extend to generating a series of prime numbers or checking for primes in a range. This article covers various techniques to implement a C program to check prime numbers using loops, functions, recursion, and mathematical optimizations like square root checking.For an input n = 17, 17 is prime because 17 cannot be divided by any integers other than 1 and by itself. Thus, it is a prime number.

For an input n = 21, 21 is NOT prime; it has other divisors, which violate the definition, in this case, 3 and 7. Hence, it is not prime.

Prime Number Program in C Using For Loop

The simplest prime number check in C is performed by using for loop. This approach checks each integer from 2 to half of the original number to see if any of these numbers evenly divides the given number. If so, then it is determined that the number is not prime.

Here’s the prime number code in C using a for loop:

#include <stdio.h>

int main() {
    int i, num, temp = 0;

    // Read input from the user
    printf("Enter any number to check for Prime: ");
    scanf("%d", &num);

    // Special case: 1 is not a prime number
    if (num <= 1) {
        printf("%d is not a prime number.\n", num);
        return 0;
    }

    // Loop from 2 to num/2
    for (i = 2; i <= num / 2; i++) {
        // Check if num is divisible by any number
        if (num % i == 0) {
            temp++;
            break; // No need to check further
        }
    }

    // Check for the value of temp
    if (temp == 0) {
        printf("%d is a Prime number.\n", num);
    } else {
        printf("%d is not a Prime number.\n", num);
    }

    return 0;
}

Output:

Enter any number to check for Prime: 7
7 is a Prime number .

This program checks if a number is divisible by any number from 2 up to (n-1) through a for loop. If it finds any divisor, the number is not prime. Otherwise, it is prime.

C Program to Check Prime Number Using While Loop

A C program to check prime numbers can also be written using a while loop. This approach iterates through potential divisors until either a divisor is found (proving the number is not prime) or the loop finishes.

Here’s the prime number in C using a while loop:

#include <stdio.h>

int main() {
    int i, num, prime = 0;

    // Prompt the user to enter a number
    printf("\nEnter the number: ");
    scanf("%d", &num);

    // Special case: Numbers less than or equal to 1 are not prime
    if (num <= 1) {
        printf("\nThis number is Not Prime.\n");
        return 0;
    }

    // Check divisors from 2 to num/2
    for (i = 2; i <= num / 2; i++) {
        if (num % i == 0) {
            prime++;
            break; // Stop checking if a divisor is found
        }
    }

    // Determine if the number is prime
    if (prime == 0) {
        printf("\nThis number is Prime.\n");
    } else {
        printf("\nThis number is Not Prime.\n");
    }

    return 0;
}

Output:

Enter number: 33
This number is Not Prime
Process returned 0(0X0)  execution time:3.535 s
Press any key to continue.

Here, a while loop is used to test divisibility, starting from 2 and stopping when a divisor is found or when the loop exceeds (n-1). The result is determined based on whether any divisors were found.

Prime Number Program in C Using If-Else

An if-else structure offers a straightforward way to check whether a number is prime. By explicitly checking conditions like whether the number is less than 2 or divisible by smaller numbers, the program determines primality efficiently.

Example code for prime in C program:

#include <stdio.h>

int main() {
    int number, isPrime;

    // Prompt the user for input
    printf("Enter a number: ");
    scanf("%d", &number);

    // Check if the number is less than or equal to 1
    if (number <= 1) {
        printf("%d is not a prime number.\n", number);
    } else {
        isPrime = 1;  // Assume the number is prime

        // Check for factors from 2 to number / 2
        for (int i = 2; i <= number / 2; i++) {
            if (number % i == 0) {
                isPrime = 0;  // If a factor is found, it's not prime
                break;        // No need to check further
            }
 }

        // Print whether the number is prime or not
        if (isPrime) {
            printf("%d is a prime number.\n", number);
        } else {
            printf("%d is not a prime number.\n", number);
        }
    }

    return 0;
}

Output:

Enter a number: 98768
98768 is not a prime number
Process returned 0(0X0)  execution time : 6.721 s
press aany key to continue.

The program uses if-else conditions to check divisibility. If any divisor is found, it immediately concludes the number is not prime. Otherwise, it outputs the number as prime.

C Program to Print Prime Numbers Using Functions

Using functions to check and print prime numbers makes the program modular and reusable. The function isolates the logic for primality, simplifying the main program.

Here’s a program for prime no. in C using functions:

#include <stdio.h>

// Function to check if the number is prime
int isPrime(int number) {
    // Check if the number is less than or equal to 1
    if (number <= 1) {
        return 0;  // Not a prime number
    }
    
    // Check for factors from 2 to number / 2
    for (int i = 2; i <= number / 2; i++) {
        if (number % i == 0) {
            return 0;  // Not a prime number
        }
    }
    
    return 1;  // It's a prime number
}

int main() {
    int number;

    // Prompt the user to enter a number
    printf("Enter a number: ");
    scanf("%d", &number);

    // Check if the number is prime and print the result
    if (isPrime(number)) {
        printf("%d is a prime number.\n", number);
    } else {
        printf("%d is not a prime number.\n", number);
    }

    return 0;
}

Output:

Enter any number: 11
11 is a prime number
process returned 0(0X0)  execution time : 6.573 s
press any key to continue.

This program defines a function to check primality and calls it repeatedly for a range of numbers. It prints all prime numbers in that range.

C Program to Check Prime Number Using Recursion

Recursion allows a function to call itself to solve even more minor instances of the problem you input. In the case of primes, a recursive function can iterate through potential divisors to check for divisibility.

Example code for prime no. in C using recursion:

#include <stdio.h>

// Recursive function to check if a number is prime
int isPrimeRecursive(int number, int divisor) {
    // Base case: If the number is less than or equal to 1, it's not prime
    if (number <= 1) {
        return 0;
    }

    // Base case: If divisor reaches 1, and no divisors were found, the number is prime
    if (divisor == 1) {
        return 1;
    }
 // If the number is divisible by the divisor, it's not prime
    if (number % divisor == 0) {
        return 0;
    }

    // Recursively call the function with divisor reduced by 1
    return isPrimeRecursive(number, divisor - 1);
}

int main() {
    int number;

    // Prompt the user to enter a number
    printf("Enter a number: ");
    scanf("%d", &number);

    // Check if the number is prime and print the result
    if (isPrimeRecursive(number, number / 2)) {
        printf("%d is a prime number.\n", number);
    } else {
        printf("%d is not a prime number.\n", number);
    }

    return 0;
}

Output:

Enter a number: 6787
6787 is a prime number
Process returned 0(0X0)  execution time: 3.080 s
press any key to continue.

It uses the recursive function to check to see if the number is divisible, it works to see whether the number will divided by the small numbers until there is a divisor or ensures that the number is a prime number.

C Program to Check Prime Numbers in a Given Range

This prime series program in C checks for all prime numbers within a specified range by iterating through each number and applying a primality check.

#include <stdio.h>

// Function to check if a number is prime
int isPrime(int number) {
    if (number <= 1) {
 return 0;  // Not prime if the number is less than or equal to 1
    }

    // Check divisibility from 2 to number/2
    for (int i = 2; i <= number / 2; i++) {
        if (number % i == 0) {
            return 0;  // Not prime if divisible by any number other than 1 and itself
        }
    }
    return 1;  // Prime number
}

int main() {
    int start, end;

    // Get the range from the user
    printf("Enter the range (start and end): ");
    scanf("%d %d", &start, &end);

    printf("Prime numbers between %d and %d are:\n", start, end);

    // Loop through the range and check for prime numbers
    for (int i = start; i <= end; i++) {
        if (isPrime(i)) {
            printf("%d ", i);  // Print the prime number
        }
    }

    printf("\n");

    return 0;
}

Output:

Enter the range (start and end): 888 1456
prime numbers between 888 and 1456 are:
907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453.
Process returned are 0(0X0)  execution time : 12.814 s
press any key to continue

This code iterates through a range of numbers, checking each one for primality using a loop or a helper function. It prints all the prime numbers in that range.

C Program to Print Prime Numbers Using Sqrt(N)

Using the square root of the number reduces the number of iterations significantly. This method checks divisibility only up to √N.

Example C code for prime number:

#include <stdio.h>
#include <math.h>

// Function to check if a number is prime
int isPrime(int number) {
    if (number <= 1) {
        return 0;  // Not prime if the number is less than or equal to 1
    }

    // Check divisibility from 2 to sqrt(number)
    for (int i = 2; i <= sqrt(number); i++) {
        if (number % i == 0) {
            return 0;  // Not prime if divisible by any number other than 1 and itself
        }
    }
    return 1;  // Prime number
}

int main() {
    int number;

    // Get the number from the user
    printf("Enter a number: ");
    scanf("%d", &number);

    // Check if the number is prime and print the result
    if (isPrime(number)) {
        printf("%d is a prime number.\n", number);
    } else {
        printf("%d is not a prime number.\n", number);
    }

    return 0;
}

Output:

Enter any number: 9876
9876 is not a prime number.
Process returned 0 (0X0)  execution time: 4.741 s
press any key to continue.

This optimised program checks divisors only up to the square root of the number, reducing unnecessary iterations. If no divisors are found in this range, the number is prime.

Conclusion

Understanding and implementing a prime number program in C is a fundamental step in learning programming. It introduces essential concepts like loops, recursion, modularity, and mathematical logic. Whether it’s checking a single number or generating a prime series, these programs lay the foundation for more advanced algorithms and problem-solving techniques.

Frequently Asked Questions

1. What’s a prime number?

Basically, any number is said to be a prime number if it is greater than 1 and has only two divisors: one and itself.

2. How does a loop-based prime number check work?

A loop iterates through potential divisors and checks divisibility. If no divisors are found, the number is prime.

3. Why is the sqrt(N) method efficient for prime checks?

The square root method reduces the number of iterations, improving efficiency for large numbers.

4. Can recursion be used to check prime numbers?

Yes, recursion simplifies the program by breaking down the problem into smaller checks.

5. How do I generate a series of prime numbers in C?

Use a loop to iterate through the range and apply a primality check for each number.

Read More Articles

Chat with us
Chat with us
Talk to career expert