Program to find sum of series 1 + 2 + 3 +……+ n in C++
#include
#include
using namespace std
int main()
{
int i,n,sum=0;
cout<<"1+2+3+......+n";
cout<<"\nEnter the value of n:"; cin>>n;
for(i=1;i<=n;++i)
sum+=i;
cout<<"\nSum="<<sum;
return 0;
}
Sum is the simplest thing in mathematics, but it is the hardest thing to be calculated. In this article, I will give you an idea of how you can calculate the sum of series 1+2+3+…+n.
We will use the below given code for this purpose.
#include
using namespace std;
int main()
{
int i,j,k;
for(i=1;i<=10;i++)
cout<<i<<"\t";< p=""></i<<"\t";<>
cout<<endl;< p=""></endl;<>
for(j=1;j<=10;j++)
cout<<j<<"\t";< p=""></j<<"\t";<>
cout<<endl;< p=""></endl;<>
for(k=1;k<=10;k++)
cout<<k<<"\t";< p=""></k<<"\t";<>
cout<<endl;< p=""></endl;<>
return 0;
}
It will show the output as 1 2 3 4 5 6 7 8 9 10
Now, I will explain the concept in detail.
The above code is the basic structure of the program and it is the most important thing in the program.
i is the loop control variable.
j is the loop counter.
k is the loop iterator.
The condition of the loop is i<=10 and if the condition is true then it will run the inner loop and again the condition will be checked.
If the condition is false then it will break the loop and return back to the outer loop.
Now, the outer loop will be executed from 1 to 10 and then it will be followed by the inner loop which will start from 1 to 10. So, the output will be as follows.
1 2 3 4 5 6 7 8 9 10
In the first iteration, j will be equal to 1, then the condition of the inner loop will be checked and it will print 1,2,3,4,5,6,7,8,9,10
In the second iteration, j will be equal to 2, then the condition of the inner loop will be checked and it will print 1,2,3,4,5,6,7,8,9,10
And so on and finally it will print the last 10 numbers of the series.
Conclusion:
This is the simplest and the most effective program to find the sum of the series 1+2+3+…+n.
If you have any doubts regarding this program then please let me know in the comment section.