What's the error?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include<iostream.h>
#include<conio.h>
void main()
{
 clrscr(); int choice, x, N, u, temp; float sum;
 cout<<"1. x+x^2+x^3+x^4....N times"<<endl<<"2. u+(u^2/2!)+(u^3/3!).....N times"<<endl<<"3. 2+(2+4)+(2+4+6)...N times"<<endl<<"Enter your choice:";
 cin>>choice;
 switch(choice)
 {
  case 1:
      {
	 cout<<"Enter N: ";
	 cin>>N;
	 cout<<"Enter x: ";
	 cin>>x;
	 for(int i=0; i<N; i++)
	 { sum+=x;
	   x*=x;
	 }
	 cout<<"The sum of the series is: "<<sum; 
	 break;
      }//Case 1 closes.
  case 2:
      {
	cout<<"Enter N: ";
	cin>>N;
	cout<<"Enter u: ";
	cin>>u;
	for(int i=2; i<(N+2); i++)
	{
	 sum+=u;
	 u*=(u/i);
	}
	cout<<"The sum of the required series is:"<<sum;  
	break;
      }//Case 2 closes.
  case 3:
      {
       cout<<"Enter N: ";
       cin>>N;
       for(int i=2, k=2; i<(N+2); i++, k++)
       {
	temp=i;
	sum+=temp;
	temp*=k;
       }
       cout<<"The sum of the series is:"<<sum;                  
	   break;
      }//Case 3 closes.
  default: cout<<"Wrong Entry"<<endl;
 }//Switch case closes.
 getch();
}//void main() closes. 

The output comes out to be:

1. x+x^2+x^3+x^4....N time
2. u+(u^2/2!)+(u^3/3!).....N times
3. 2+(2+4)+(2+4+6)...N times
Enter your choice:1
Enter N: 3
Enter x: 2
The sum of the series is: 22
(2+4+8 not equal to 22)
But it should be like:
1. x+x^2+x^3+x^4....N time
2. u+(u^2/2!)+(u^3/3!).....N times
3. 2+(2+4)+(2+4+6)...N times
Enter your choice:1
Enter N: 3
Enter x: 2
The sum of the series is: 14
(2+4+8=14)
Where are you initialising sum? I don't see you doing that anywhere.

Did your compiler not warn you about using it before you initialise it?
Ok i did that..and no the compiler didnt warn me..
But still the output comes as above..22 not 14
The problem is in line 18. You multiply the current value of x by itself instead of the original value of x. So you are adding 2 + (2*2) + (4*4). You need to copy the original value of x to, say Y, and then change line 18 to
y *= x;
Oh yes..thanks :)
Topic archived. No new replies allowed.