C++ Program To Find Sum of First N Natural Numbers
Last Updated :
02 Aug, 2023
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.
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.
- 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++
#include <iostream>
using namespace std;
int findSum( int n)
{
int sum = 0;
for ( int i = 1; i <= n; i++)
sum = sum + i;
return sum;
}
int main()
{
int n = 5;
cout << findSum(n);
return 0;
}
|
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...