Sum of the series: x +x^2/2!+x^4/4!+x^6/6!+...output problem.

My Turbo C++ 4.5 is giving incorrect result for the following programming code which is meant to sum the series x + x^2/2! + x^4/4! + x^6/6! upto 'n' terms.It gives the correct result for 'n=1' only.What is the problem in the following code? Please help.

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
#include<iostream.h>
#include<math.h>
int main()
{ int n,k,temp;
  float x,sum=x,fact=1.0,div;

  cout << "Enter the value of x: ";
  cin >> x;
  cout << "Enter the value of n: ";
  cin >> n;

if(n==1)
{ cout << "The sum of the series x + x^2/2! + x^4/4! +... upto " << n << " term is: " << x; }
if(n!=1)
{for(int i=1;i<n;i++)
  { k=2*i;
	 for(i=1;i<=k;i++)
	 {fact=fact*i;}
	 temp=pow(x,k);
	 div=temp/fact;
	 sum+=div;
	 }
	 cout << "The sum of the series x + x^2/2! + x^4/4! +... upto " << n << " terms is: " << sum;
	 }

return 0;
}
Last edited on
You should clean up your code indentation. Debugging shall be a lot easier.

I see three major problems:

1. float x,sum=x,fact=1.0,div;
This is undefined behaviour. x is not initialized and you are assigning it to sum. Instead move this assignment after reading the value of x.

2. You are using same loop variable for the two nested loops (i).

3. You are not initializing fact to be 1 before the inner loop.

Also, you are using deprecated headers. Use <iostream> and <cmath>.

1
2
3
4
5
6
7
8
9
10
11
12
13

//Note the code indentation.

if (n != 1) // You can simply say 'else' here
{
    for(int i=1;i<n;i++)
    {  
        k=2*i;
        fact = 1; // add this
	for(int j = 1; j <= k; j++ ) // change the inner loop variable
	{
            fact=fact*j;
        }


Full Code:
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
#include<iostream>
#include<cmath>

int main()
{ 
    int n,k,temp;
    float x, sum, fact=1.0, div;

    cout << "Enter the value of x: ";
    cin >> x;
    sum = x; // here x has a value provided you gave a valid input.
    cout << "Enter the value of n: ";
    cin >> n;

    if (n==1)
    { 
        cout << "The sum of the series x + x^2/2! + x^4/4! +... upto " << n << " term is: " << x; 
    }
    else
    {
        for(int i=1;i<n;i++)
        { 
            k=2*i;
            fact = 1; // add this
	    for(int j = 1; j <= k; j++ ) // change the inner loop variable
	    {
                fact=fact*j;
            }
            temp=pow(x,k);
	    div=temp/fact;
	    sum+=div;
	}
        cout << "The sum of the series x + x^2/2! + x^4/4! +... upto " << n << " terms is: " << sum;
    }
    return 0;
}

Last edited on
Thanks, abhishekm71. :) Resolved. :)
Topic archived. No new replies allowed.