# Thread: Help C programming that reads value of x and n?

1. ## Help C programming that reads value of x and n?

C program that reads the value of x and n from the keyboard and then approximately computes the value of cos(x) using the following formula:

Cosx = 1 - x^2/2! + x^4/4! - x^6/6! .....+ (-1)^n x^2n/(2n)!

(Written)
cos of x equal 1 minus x square over two ! plus x to the fourth over 4! minus x to the sixth over six !.......plus(minus one) to the n...
x squared n over (two n) !

Can you all check if the middle part of the code is correct.

Code:
```#include <stdio.h>
#include <math.h>
int main (void)
{

/*Declare variables*/
int i, n;
double x, cos;

printf("Enter the value of x and n: ");
scanf("%lf %d", &x, &n);

/* loop to compute cosx using above formula*/

/*Please can  you all check this part"*/

double cos=1;
int count=2;
int p=1;
int fact=1;
int i,j;

for( i = 0; i <= n; i=i+2)
{
if (i!=0)
{
//for x^2, x^4, x^6....
for(j=1;j<=i;j++)
p=p*x;

//for factorial
for(j=1;j<=i;j++)
fact=fact*j;

if(count%2==0)
cos -= p/fact;
else
cos += p/fact;
}
count++;
}

printf("Approximate cosx is %lf when n=%d \n", cosx, n);
printf("Cos(x) in math lib returns %lf \n", Cos(x));

system ("pause")

return 0;

}```

2. It would help a whole lot if the code was indented so that we could see what it actually looks like.

--
Mats

3. It would be simpler for you to use print statements for each iteration of factorial and for the values of x^n to determine if the loops are equating the correct values or you!

4. Originally Posted by kcpilot
It would be simpler for you to use print statements for each iteration of factorial and for the values of x^n to determine if the loops are equating the correct values or you!
Or use a debugger instead of print statements.

5. I indented the code hope it helps.

Code:
```#
#include <stdio.h>
#
#include <math.h>
#
int main(void)
#
{
#

#
/*Declare variables*/
#
int i, n;
#
double x, cos;
#

#
printf("Enter the value of x and n: ");
#
scanf("%lf %d", &x, &n);
#

#

#
/* loop to compute cosx using above formula*/
#

#
/*Please can you all check this part"*/
#

#
double cos = 1;
#
int count = 2;
#
int p = 1;
#
int fact = 1;
#
int i, j;
#

#
for (i = 0; i <= n; i = i + 2) {
#
if (i != 0) {
#
//for x^2, x^4, x^6....
#
for (j = 1; j <= i; j++)
#
p = p * x;
#

#
//for factorial
#
for (j = 1; j <= i; j++)
#
fact = fact * j;
#

#
if (count % 2 == 0)
#
cos -= p / fact;
#
else
#
cos += p / fact;
#
}
#
count++;
#
}
#

#

#

#

#

#

#

#

#

#

#

#

#

#
printf("Approximate cosx is %lf when n=%d \n", cosx, n);
#
printf("Cos(x) in math lib returns %lf \n", Cos(x));
#

#

#
system("pause")
#

#
return 0;
#

#
}```

6. I'm not entirely sure what you are doing, but it looks even more rubbish than before.

--
Mats