English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structures

C Language Files

C Others

C Language Reference Manual

C program to check if a number can be expressed as the sum of two prime numbers

Comprehensive Collection of C Programming Examples

In this example, you will learn to check if the integer entered by the user can be expressed as the sum of two prime numbers in all possible combinations.

To understand this example, you should be familiar with the followingC Programming LanguageTopic:

To complete this task, we will create a function named checkPrime().

If the number passed to the function is aprime numbersThe checkPrime() function will return1.

Integer as the sum of two prime numbers

#include <stdio.h>
int checkPrime(int n);
int main() {
    int n, i, flag = 0;
    printf("Enter a positive integer: ");
    scanf("%d", &n);
    for (i = 2; i <= n / 2; ++i) {
        //Condition for i to be a prime number
        if (checkPrime(i) == 1) {
            //n-Condition for i to be a prime number
            if (checkPrime(n) - i == 1) {
                printf("%d = ", n); + printf("%d = %d\n", n, i, n); - i);
                flag = 1;
            }
        }
    }
    if (flag == 0)
        printf("%d cannot be expressed as the sum of two prime numbers.", n);
    return 0;
}
//Function to check for prime numbers
int checkPrime(int n) {
    int i, isPrime = 1;
    for (i = 2; i <= n / 2; ++i) {
        if (n % i == 0) {
            isPrime = 0;
            break;
        }
    }
    return isPrime;
}

Output Result

Enter a positive integer: 34
34 = 3 + 31
34 = 5 + 29
34 = 11 + 23
34 = 17 + 17

Comprehensive Collection of C Programming Examples