C++ Program To Find Sum of First N Natural Numbers
Last Updated :
02 Aug, 2023
Improve
Try it on GfG Practice
Natural numbers are those positive whole numbers starting from 1 (1, 2, 3, 4, ...). In this article, we will learn to write a C++ program to calculate the sum of the first N natural numbers.
-660.png)
Algorithm
- Initialize a variable sum = 0.
- Run a loop from i = 1 to n.
- Inside the loop, add the value of i to the current value of sum for each iteration.
- sum = sum + x
- After the loop, the variable sum will hold the sum of the first n natural numbers.
C++ Program to Find the Sum of Natural Numbers
// C++ program to find sum of first
// n natural numbers.
#include <iostream>
using namespace std;
// Returns sum of first n natural
// numbers
int findSum(int n)
{
int sum = 0;
for (int i = 1; i <= n; i++)
sum = sum + i;
return sum;
}
// Driver code
int main()
{
int n = 5;
cout << findSum(n);
return 0;
}
Output
15
Complexity Analysis
- Time Complexity: O(n)
- Auxiliary Space: O(1)
Refer to the complete article Program to find the sum of first n natural numbers for optimized methods to find the sum of N natural numbers.