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

## C++ For Loop: Exercise-33 with Solution

Write a program in C++ to Check Whether a Number can be Express as Sum of Two Prime Numbers.

**Pictorial Presentation:**

**Sample Solution**:-

**C++ Code :**

```
#include <iostream>
using namespace std;
int main()
{
int n, i, flg1 = 1, flg2 = 1, flg3 = 0, j;
float sum = 0;
cout << "\n\n Check Whether a Number can be Express as Sum of Two Prime Numbers:\n";
cout << "------------------------------------------------------------------------\n";
cout << " Input a positive integer: ";
cin >> n;
for (i = 2; i <= n / 2; i++)
{
/*---------- check for prime---------------*/
flg1 = 1;
flg2 = 1;
for (j = 2; j < i; j++)
{
if (i % j == 0)
{
flg1 = 0;
j = i;
}
}
for (j = 2; j < n - i; j++)
{
if ((n - i) % j == 0)
{
flg2 = 0;
j = n - i;
}
}
if (flg1 == 1 && flg2 == 1)
{
cout << n << " = " << i << " + " << n - i << endl;
flg3 = 1;
}
}
if (flg3 == 0)
{
cout << n << " can not be expressed as sum of two prime numbers." << endl;
}
}
```

Sample Output:

Check Whether a Number can be Express as Sum of Two Prime Numbers: ------------------------------------------------------------------------ Input a positive integer: 20 20 = 3 + 17 20 = 7 + 13

**Flowchart: **

**C++ Code Editor:**

** Contribute your code and comments through Disqus.**

**Previous:** Write a program in C++ to find the Sum of GP series.

**Next:** Write a program in C++ to find the length of a string without using the library function.

**What is the difficulty level of this exercise?**

## C++ Programming: Tips of the Day

**Which is faster: Stack allocation or Heap allocation**

Stack allocation is much faster since all it really does is move the stack pointer. Using memory pools, you can get comparable performance out of heap allocation, but that comes with a slight added complexity and its own headaches.

Also, stack vs. heap is not only a performance consideration; it also tells you a lot about the expected lifetime of objects.

Ref : https://bit.ly/3COrdfj

**Exercises: Weekly Top 16 Most Popular Topics**- SQL Exercises, Practice, Solution - JOINS
- SQL Exercises, Practice, Solution - SUBQUERIES
- JavaScript basic - Exercises, Practice, Solution
- Java Array: Exercises, Practice, Solution
- C Programming Exercises, Practice, Solution : Conditional Statement
- HR Database - SORT FILTER: Exercises, Practice, Solution
- C Programming Exercises, Practice, Solution : String
- Python Data Types: Dictionary - Exercises, Practice, Solution
- Python Programming Puzzles - Exercises, Practice, Solution
- C++ Array: Exercises, Practice, Solution
- JavaScript conditional statements and loops - Exercises, Practice, Solution
- C# Sharp Basic Algorithm: Exercises, Practice, Solution
- Python Lambda - Exercises, Practice, Solution
- Python Pandas DataFrame: Exercises, Practice, Solution
- Conversion Tools
- JavaScript: HTML Form Validation