/* Lab 7 assignment: do-while and for loops to calculate the sum of a series
do-while loop implementation
---------------------------------------------
Patrick Schmid pds2
February 8, 2006
Lab 7 do-while solution
Lab instructor: Patrick Schmid
Lab section: 10 & 11
Purpose: Calculate the value of exp(x) using the Taylor Series expansion.
         Allow the user to specify the number of terms in the Taylor Series and x.

Algorithm: 
Taylor Series expansion of exp(x) using i terms:
	     exp(x) = 1 + x + (x^2) / 2! + ... + (x^i) / i!

1) We calculate one term per loop and add it to the sum of all terms (expX).
   Increment n by 1 at the end of each loop.
2) The 1st term is always 1. We can therefore start the loop with the 
   2nd term (n=1). We can store the value 1 in expX and factorial 
3) term = x^n / n!
   x^n is easy to calculate: pow(x, n)
4) factorial is harder to calculate
   5! = 5 * 4 * 3 * 2 * 1 or 5! = 1 * 2 * 3 * 4 * 5
   As we are incrementing n by 1 each time through the loop (starting at n=1),
   we can build the factorial using the 2nd expression from left to right.
   Therefore, store the value of the factorial in a variable and multiply
   it at the beginning of each loop by n.
*/


#include <iostream.h>
#include <math.h>

void main() {
	double x; //x
	int numberOfTerms; //number of terms in Taylor series expansion
	int n; //n in Taylor series expansion 
		   //= number of current term in expansion = exponent and factorial
	double expX; //stores already calculated values of expansion
	double factorial; //stores result of factorial

	//tell the user what this program does
	cout<<"This program calculates exp(x) using the Taylor series expansion"<<endl;
	
	//get input
	cout<<"Please enter x: ";
	cin>>x;
	cout<<"Please enter the number of terms to use: ";
	cin>>numberOfTerms;

	//echo print
	cout<<"x = "<<x<<endl;
	cout<<"Number of terms to use for the Taylor series expansion of exp(x): "<<numberOfTerms<<endl;

	n=1; //first term (n=0) is always 1: 1=pow(x,0) / 0!, so we can start the loop
		 //with the second term (n=1)
	expX=1; //store first term in expX
	factorial=1; //0! = 1

	do {
		//multiply stored factorial with next number
		factorial*=n;

		//calculate next term in Taylor series expansion
		expX += pow(x, n) / factorial;

		//increment n (current term counter)
		n++;


	} while (n <= numberOfTerms); //repeat numberOfTerms-times until n>numberOfTerms
								 

	//output results
	cout<<endl<<"exp(x) calculcated with Taylor series expansion: "<<expX<<endl;
	cout<<"exp(x) calculated with math.h exp(x) function: "<<exp(x)<<endl;
}

