Numbers 1, 2, 3, …., n are known as natural numbers. This program takes the value of n and finds the sum of first n natural numbers.
For example, If user enters 5 as the value of n then the sum of first n(n=5) natural numbers would be:
1+2+3+4+5 = 15
Example: Program to calculate the sum of n natural numbers
To understand this program you should have the knowledge of C++ while loop.
#include using namespace std; int main(){ int n, sum=0; cout<<"Enter the value of n(should be a positive integer): "; //Storing the input integer value into the variable n cin>>n; /* If user enters value of n as negative then display an * error message to user that the value of n is invalid */ if(n<=0){ cout<<"Invalid value of n"; } else{ // We are using while loop to calculate the sum int i=1; while(i<=n){ sum=sum+i; i++; } cout<<"Sum of first n natural numbers is: "<<sum; } return 0; }
Output:
Enter the value of n(should be a positive integer): 5 Sum of first n natural numbers is: 15
You can also use for loop for this program. You just need to replace this part:
int i=1; while(i<=n){ sum=sum+i; i++; }
with this:
for(int i = 1; i <= n; i++) { sum = sum+i; }
We can solve this problem using recursion as well, you can find the program here: Program to find the sum of n natural numbers using recursion.
Leave a Reply