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

549
views #### In this Programme, you’ll learn C++ Program to Check Whether a Number can be Express as sum of prime numbers.

To nicely understand this example to find sum of prime numbers, you should have the knowledge of following C++ programming topics:

1. for Loop
2. C++ if, if…else and Nested if…else
3. Functions
4. Types of User-defined Functions

This program takes a positive integer from user and checks whether that number can be expressed as the sum of two prime numbers.
If the number can be expressed as the sum of two prime numbers, the output shows the combination of the prime numbers.

To perform this task, a user-defined function is created to check prime number.

#### Example #1: Check Whether a Number can be Expressed as a Sum of Two Prime Numbers

```#include <iostream>
using namespace std;

bool checkPrime(int n);

int main()
{
int n, i;
bool flag = false;

cout << "Enter a positive  integer: ";
cin >> n;

for(i = 2; i <= n/2; ++i)
{
if (checkPrime(i))
{
if (checkPrime(n - i))
{
cout << n << " = " << i << " + " << n-i << endl;
flag = true;
}
}
}

if (!flag)
cout << n << " can't be expressed as sum of two prime numbers.";

return 0;
}

// Check prime number
bool checkPrime(int n)
{
int i;
bool isPrime = true;

for(i = 2; i <= n/2; ++i)
{
if(n % i == 0)
{
isPrime = false;
break;
}
}

return isPrime;
}```

After Compiling the above code we get Output

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

Ask your questions and clarify your/others doubts on how to Find sum of prime numbers using Recursion by commenting or posting on our forum. Documentation

SHARE