C++ Program to find the sum of prime numbers between 1 to n


In this program, You will learn how to find the sum of prime numbers between 1 to n in C++.


10th: 2 + 3 + 5 + 7 = 17

Example: How to find the sum of prime numbers between 1 to n in C++.

#include<iostream>
using namespace std;

int main() {

    int upto, i, j, p, s = 0;

    cout << "Enter a number:";
    cin>>upto;

    for (i = 2; i <= upto; i++) {
        p = 1;
        j = 2;
        while (j < i) {
            if (i % j == 0) {
                p = 0;
                break;
            }
            j++;
        }
        if (p == 1) {
            s = s + j;
        }
    }
    cout << "Sum of prime numbers:" << s;

    return 0;
}

Output:

Enter a number:10
Sum of prime numbers:17