# Geeksforgeeks Solution For " Sum of an AP "

GeeksforGeeks Solution For School Domain .Below You Can Find The Solution Of Basic ,Easy ,Medium ,Hard .You Can Also Direct Submit Your Solution to Geeksforgeeks Same Problem .You Need to login then you can submit you answers

Problem :- Write a program to print sum of an AP with n terms with first term a and common difference d.

Solution :-

Method 1 :-

#include <iostream>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
int n,a,b,d,sum=0;
cin>>n;
cin>>a>>d;
sum=(n*((2*a)+((n-1)*d)))/2;
cout<<sum<<endl;
}
return 0;
}

Method 2 :-

#include <iostream>
#include<cstdio>
#include <cmath>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
int n,a,p,r;
long double sum=0.0;
cin>>n;
cin>>a>>r;
if(r==1){
cout<<a*n<<endl;
continue;
}
p=pow(r,n);
sum=(a*(1-p)/(1-r));
sum/=1.0;
//cout<<sum<<endl;
printf("%Lf\n", sum);

}
return 0;

}

Method 3 :-

#include <stdio.h>
#include <math.h>

double GP(int a, int r, int n)
{
return (a*pow(r,n)-a)/(r-1);
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
double N, i, a, r;
scanf("%lf\n",&N);
scanf("%lf %lf",&a,&r);
if(r==1)
{
printf("%lf\n",a*N);
}
else
{
printf("%lf\n", GP(a, r, N));
}
}
return 0;

}

Output:-

Previous Post
Next Post

#### post written by: Ghanendra Yadav

Hi, I’m Ghanendra Yadav, SEO Expert, Professional Blogger, Programmer, and UI Developer. Get a Solution of More Than 500+ Programming Problems, and Practice All Programs in C, C++, and Java Languages. Get a Competitive Website Solution also Ie. Hackerrank Solutions and Geeksforgeeks Solutions. If You Are Interested to Learn a C Programming Language and You Don't Have Experience in Any Programming, You Should Start with a C Programming Language, Read: List of Format Specifiers in C.