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


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


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


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

Run it Now
#include<iostream>
using namespace std;

int main() {

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

    cout << "Enter upto Prime Numbers :";
    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 << "\nThe sum of Prime Number is :" << s;

    return 0;
}

Output:

Enter upto Prime Numbers :10
The sum of Prime Number is :17