C Program to Check Whether a Number can be Express as Sum of Two Prime Numbers - Source Code, Output & Execution Flow

C Program to Check Whether a Number can be Express as Sum of Two Prime Numbers

This C program checks whether a number can be written as the sum of two prime numbers.

#include <stdio.h>
int isPrime(int n) {
    int i;
    if (n <= 1) return 0;
    for (i = 2; i * i <= n; i++) if (n % i == 0) return 0;
    return 1;
}
int main() {
    int n, i, found = 0;
    printf("Enter a number: ");
    scanf("%d", &n);
    for (i = 2; i <= n / 2; i++) {
        if (isPrime(i) && isPrime(n - i)) {
            printf("%d = %d + %d
", n, i, n - i);
            found = 1;
        }
    }
    if (!found) printf("%d cannot be expressed as sum of two primes.
", n);
    return 0;
}
Enter a number: 34
34 = 3 + 31
34 = 5 + 29
34 = 11 + 23
34 = 17 + 17

In this program, the input is read first when required, the core logic is applied step by step, and the final result is displayed using printf(). Follow the execution flow beside the code to understand how each statement contributes to the output.

Sai Kishore Randhi, author
About the author

Sai Kishore Randhi

Embedded systems, VLSI, and chip design

Sai Kishore writes about embedded systems, VLSI, chip design, and the programming concepts behind modern hardware.

View LinkedIn profile ↗