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
- Include necessary libraries:
The program includes the iostream library to enable input and output operations.
Declare variables:
Declare two integer variables,
n
to store the input value andsum
to store the sum of natural numbers.Input:
Prompt the user to enter a positive integer using
cout
, and then store the input in the variablen
usingcin
.Calculate the sum:
Use a for loop to iterate through the natural numbers from 1 to
n
and add each number to thesum
variable.Output:
Display the sum of the first N natural numbers using
cout
.Return statement:
- 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.