C++ Program to find Sum of Series (When n is Odd/Even) – Q2
Q2. Program to find Sum of Series:
i) x-x^3/3!-x^5/5!+x^7/7!-….. x^n/n! (When n is odd)
ii) x^2/2!-x^4/4!+x^6/6!-….. x^n/n! (When n is even)
… from College notes (BCA/MCA assignments):
#include <iostream.h> #include <math.h> #include <conio.h> long Fact(long); float Odd_Series(int, int); float Even_Series(int , int); int main(){ int x, n; float sum; clrscr(); cout<<"\n Enter the Value of x: "; cin>>x; cout<<"\n Enter the Value of n: "; cin>>n; sum = Odd_Series(x, n); cout<<"\n Sum of Odd Series: "<<sum; sum = Even_Series(x, n); cout<<"\n Sum of Even Series: "<<sum; getch(); return 0; } long Fact(long f){ if(f<=0) return 1; else return (f * Fact(f-1)); } float Odd_Series(int x, int n){ int i, f; float sum = 0; for(i=1, f=0; i<=n; i=i+2, f++) sum += pow(-1, f) * pow(x, i) / Fact(i); return sum; } float Even_Series(int x, int n){ int i, f; float sum = 0; for(i=2, f=0; i<=n; i=i+2, f++) sum += pow(-1, f) * pow(x, i) / Fact(i); return sum; }
Output:
Enter the Value of x: 4
Enter the Value of n: 5
Sum of Odd Series: 1.866667
Sum of Even Series: -2.666667
Categories: Cpp
Cpp, Sum of Series
Comments (0)
Trackbacks (0)
Leave a comment
Trackback