C++ Code To Find The Sum Of A Series



C++ Code To Find The Sum  Of  A Series
===============================


#include <iostream>
using namespace std;
int main()

{cout<<"*************** Sum of the Series ****************"<<endl<<endl;
    int any;
    cout<<"Enter 1 to Proceed and 0 to exit : ";
    cin>>any;
    if(any!=0){
    do{
   int a,ans=0,cd,n;
cout<<"\nEnter the first number of the series : ";
cin>>a;
    cout<<"\nEnter the total number of terms : ";
    cin>>n;
    cout <<"\nEnter the common difference : ";
    cin>>cd;

    for(int x=a;x<=(a+(n-1)*cd);x+=cd ){
        ans+=x;
   }
 cout<<"\nThe sum of the series is : "<<ans<<endl;

 cout<<"========================================================="<<endl<<endl;
cout<<"\nEnter 1 to Proceed and 0 to exit : ";
    cin>>any;
    }while(any!=0);
    }
}



Logic:
========

Sum of a series = n/2(2f+(n-1)d)

where n: number  of terms
           f: first term in sequence
           d: difference between consecutive terms

No comments:

Post a Comment