Question -
Given an Arithmetic progression , we have to find the sum of progression till n element.
Example -
Input : arr[] = {1, 2, 3} n = 10
Output : 55
Approach -
We calculate the sum using standard formula.
Implementation -
//sum of given arithmetic progression
#include<iostream>
using namespace std;
void sum(int arr[],int n)
{
int a=arr[0];
int d=arr[1]-arr[0];
int sum;
sum=(n*(2*a+(n-1)*d))/2;
cout<<"Sum is : "<<sum<<endl;
}
int main(int argc, char *argv[])
{
int n;
cout<<"Enter n : ";cin>>n;
int arr[3];
cout<<"Enter first 3 elements : "<<endl;
for(int i=0;i<3;i++)
cin>>arr[i];
sum(arr,n);
return 0;
}
Time complixity - O(1)
Comments
Post a Comment