Sum of n Natural Numbers
Program to calculate sum of first n natural numbers
BeginnerTopic: Loop Programs
C++ Sum of n Natural Numbers Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#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 of first " << n << " natural numbers = " << sum << endl;
return 0;
}Output
Enter a positive integer: 10 Sum of first 10 natural numbers = 55
Understanding Sum of n Natural Numbers
This program calculates the sum of natural numbers from 1 to n using a for loop. We initialize sum to 0, then add each number from 1 to n to the sum. The result is the sum of the arithmetic series: 1 + 2 + 3 + ... + n.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.