Write a C++ Program to find the sum of an AP series up-to a given number and display the result on the screen.
Program Code:
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
int x, n, m;
int d, i;
int sum=0;
cout<<"Enter the first number of the AP series : ";
cin>>x;
cout<<endl;
cout<<"Enter total number of terms in the AP series : ";
cin>>n;
cout<<endl;
cout<<"Enter the common difference between each number of the AP series : ";
cin>>d;
cout<<endl;
sum=(n * ( 2 * x + (n - 1 ) * d ) ) / 2;
m = x + ( n - 1 ) * d;
cout<<"Sum of the given AP series is : ";
for(i = x; i <= m; i = i+d)
{
if(i != m)
{
cout<<i<<" + ";
}
else
{
cout<<i<<" = "<<sum;
}
}
return 0;
}
The program output is tested on www.jdoodle.com
Output:
Enter the first number of the AP series : 1
Enter total number of terms in the AP series : 20
Enter the common difference between each number of the AP series : 2
Sum of the given AP series is : 1 + 3 + 5 + 7 + 9 + 11 + 13 + 15 + 17 + 19 = 100
Thanks
Mukesh Rajput
Post A Comment:
0 comments: