Calculate Sum of Natural Numbers in C++

Codeblocks Visual Studio Code

Certainly! To calculate the sum of natural numbers in C++, you can use a loop to add up the numbers from 1 to a specified limit. Here's an example program:

#include <iostream>
using namespace std;

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

    // Get the limit 'n' from the user
    cout << "Enter a positive integer 'n': ";
    cin >> n;

    // Calculate the sum of natural numbers
    for (int i = 1; i <= n; ++i) {
        sum += i;
    }

    cout << "Sum of natural numbers from 1 to " << n << " is: " << sum << endl;

    return 0;
}

The program prompts the user to enter a positive integer n.

It then uses a for loop to iterate through the numbers from 1 to n.

Inside the loop, it adds each number to the sum variable.

Finally, it prints out the sum of natural numbers.

For example, if the user enters 5, the program will calculate the sum of natural numbers from 1 to 5:

Sum of natural numbers from 1 to 5 is: 15

You can modify this program to calculate the sum for different values of n by changing the user input.

Comments
Loading...
Sorry! No comment found:(

There is no comment to show for this.

Leave your comment
Tested Versions
  • GCC 6.3.0