Prime number

A prime number is an integer greater than 1 whose only factors are 1 and itself. A factor is an integer that can be divided evenly into another number.

Logic

To print the sum of all prime numbers up to N we have to iterate through each number up to the given number and check if the number is a prime or not if it is a prime number then simply sum it or add it in one temporary variable.

Once the outer loop is completed we have to print that temporary variable containing the sum of primes.

See also: Check whether a number is prime number or not

Program

#include <iostream>

using namespace std;

int main() {

    int num, i, upto, sum = 0;

    // Take input from user
    cout << "Find sum of prime numbers upto : ";
    cin >> upto;

    for(num = 2; num <= upto; num++) {

        for(i = 2; i <= (num / 2); i++) {

            if(num % i == 0) {
                i = num;
                break;
            }
        }

        // If the number is prime then add it.
        if(i != num) {
            sum += num;            
        }
    }

    cout << endl << "Sum of all prime numbers upto " << upto << " : " << sum;

    return 0;
}

Output

Find sum of prime numbers upto : 50
Sum of all prime numbers upto 50 : 326