Easy Tutorial
❮ Cpp Break Statement Cpp Basic Input Output ❯

C++ Example - Sum of Natural Numbers

C++ Example

Calculate the sum of 1+2+3+....+n.

Example

#include <iostream>
using namespace std;

int main()
{
    int n, sum = 0;

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

    for (int i = 1; i <= n; ++i) {
        sum += i;
    }

    cout << "Sum = " << sum;
    return 0;
}

The above program produces the following output:

Enter a positive integer: 50
Sum = 1275

C++ Example

❮ Cpp Break Statement Cpp Basic Input Output ❯