Write a C++ Program to calculate the sum of a series up to x numbers.This program calculates the sum of the series 1 + 2 + 3 +. . . . .+ x and then display the result on screen.
Program Code:
#include<iostream>
using namespace std;
int main()
{
int x, i;
int sum=0;
cout<<"Program to calculate sum 1+2+3+... x : ";
cout<<endl;
cout<<"Enter the value of x : ";
cin>>x;
cout<<endl;
sum = (x *(x+1)) / 2;
cout<<"Sum of the given series upto x number is : ";
for(i=1; i<=x; i++)
{
if(i != x)
{
cout<<i<<" + ";
}
else
{
cout<<i<<" = "<<sum;
}
}
return 0;
}
The program output is tested on www.jdoodle.com
Output:
Program to calculate sum 1+2+3+... x :
Enter the value of x : 6
Sum of the given series upto x number is : 1 + 2 + 3 + 4 + 5 + 6 = 21
Thanks
Mukesh Rajput
Post A Comment:
0 comments: