Respected Sir, Kindly help me complete a code to evaluate the series 1-1/3!+1/5!-1/7!....+/-1/n!
Code-
voidmain() { clrscr(); int fact=1,sum=0,n; cout<<"Enter the number": cin>>n; for(int i=1;i<=n;i=i+2) Here is where my confusion arises...we have to give 2 conditions for - and +.
I am sorry but you question is unclear to me and I am not sure I fully grasp where your confusion arises. I am going to guess that you mean how do you switch from + to - from iteration to iteration. If this is not what you were asking about then sorry, please post a follow up question clarifying what it is you are confused about.
If so then read on.
First note that I am not going to complete the assignment for you. I will mention a few things to point you in the right direction though.
I would have thought that you could have used several techniques here e.g. one obvious one would be a flag defined and initialised outside the for loop and set, reset and tested appropriately within the for loop body:
if (isUsingPlus) { // Do code for + term isUsingPlus = false; } else { // Do code for - term isUsingPlus = true; }
However what if I were to mention in passing that 1*-1 = -1 and -1*-1 = 1. And that you can re-write your formula:
(1/1!) + (-1/3!) + (1/5!) + (-1/7!)
Now we always add each term to the previous results and move the +/- issue to the dividend of each term - that is the dividend of each term is now 1 or -1.
So seeing this maybe you might think ah ha! I could use a variable initialised to 1 (as the first term is +1 or +1/1!) and after performing the calculations for each term, but before the loop body ends, you multiply this variable by -1.
In fact it could even be another set of for loop clauses:
for ( int i=1, dividend=1; i <= n; i += 2, dividend *= -1 )
Hope this was what you were asking about and you can move forward with your assignment. Oh, do not forget that you cannot use integers to hold the term results as in integer division 1 / n, where n > 1, gives a result of 0.
Advertisement