sum of n natural numbers

C++ Program to Find the Sum of N Natural Numbers

The following C++ program calculates the sum of the first N natural numbers.

#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;
}

Explanation of Each Step

  1. Include necessary libraries:
  2. The program includes the iostream library to enable input and output operations.

  3. Declare variables:

  4. Declare two integer variables, n to store the input value and sum to store the sum of natural numbers.

  5. Input:

  6. Prompt the user to enter a positive integer using cout, and then store the input in the variable n using cin.

  7. Calculate the sum:

  8. Use a for loop to iterate through the natural numbers from 1 to n and add each number to the sum variable.

  9. Output:

  10. Display the sum of the first N natural numbers using cout.

  11. Return statement:

  12. The main function returns 0 to indicate successful execution of the program.

Example

For example, if the user enters 5, the program will calculate the sum of the first 5 natural numbers (1 + 2 + 3 + 4 + 5) and output the result as 15.