Using For-Loop
From 1 to n, a for loop is executed. Iterator' i' represents the natural numbers from 1 to n. So, this value of i will be added to the sum during each iteration. Therefore, the sum of first 'n' Natural numbers is calculated using for loop. The following code sample demonstrates this.
#include<iostream>
using namespace std;
int main()
{
int n=10, sum=0, i;
for(i=1;i<=n;i++)
{
sum=sum+i;
}
cout<<"Sum of first "<<n<<" natural numbers is "<<sum;
return 0;
}

You can also try this code with Online C++ Compiler
Run Code
Output
Sum of first 10 natural numbers is 55

You can also try this code with Online C++ Compiler
Run Code
Time Complexity: O(n) and we run loop for n number and find the total sum.
Space Complexity: O(1)
Using Formula
The formula used to find the sum of first n natural numbers, is given as:
sum = n(n+1)/2
The following is a program that uses the above formula to calculate the sum of n natural numbers.
#include<iostream>
using namespace std;
int main() {
int n=10, sum=0;
sum = n*(n+1)/2;
cout<<"Sum of first "<<n<<" natural numbers is "<<sum;
return 0;
}

You can also try this code with Online C++ Compiler
Run Code
Output
Sum of first 5 natural numbers is 15

You can also try this code with Online C++ Compiler
Run Code
Time Complexity: O(1)
Space Complexity: O(1)
Try and compile with online c++ compiler.
Must Read Dynamic Binding in C++
Also Read - Strong number in c
FAQs
-
What is the complexity of summing a series of n natural numbers?
In this case, algorithm's complexity is calculated as the number of times addition operation is performed that is O(n).
-
Why do we use #include iostream in C++ programming?
Iostream is a file that defines all of the commands such as cout, endl, etc. We'll need to add that file if we want to use them. #include iostream> simply implies copying and pasting the code from that file into your code.
Key Takeaways
This article extensively discussed the program to calculate the sum of n natural numbers using C++. The article explains the different approaches used to find sum of natural numbers in C++. The use of formula as well as loops are explained. There are many more approaches, but these are the most efficient in terms of time and space.
Check out this problem - Two Sum Problem
We hope that this blog has helped you enhance your knowledge regarding the Sum of Natural numbers and if you would like to learn more, check out our articles on Coding Ninjas. Do upvote our blog to help other ninjas grow.
Happy Coding!