fork download
  1. /* Program to find sum of series: x – x3/!3 + x5/!5 – x7/!7 ………… ( Sin x ) */
  2.  
  3. #include <stdio.h>
  4.  
  5. float xpower(int j, int x)
  6. {
  7. int pwr = 1;
  8. for(int i = 1; i <= j; i++)
  9. pwr = pwr*x;
  10.  
  11. return pwr;
  12. }
  13.  
  14. float xfactorial(int k)
  15. {
  16. if (k == 1)
  17. return 1;
  18.  
  19. int fact = 1;
  20. for(int i = 1; i <= k; i++)
  21. fact = fact * i;
  22.  
  23. //printf("factorial of %d is %d\n", k, fact);
  24. return fact;
  25. }
  26.  
  27.  
  28. float SumOfSeries(int steps, int x)
  29. {
  30. float result = 0;
  31.  
  32. for(int i = 1; i <= steps; i = i+2)
  33. {
  34. float power = xpower(i, x);
  35. float factorial = xfactorial(i);
  36.  
  37. /* the below condition defines the sign */
  38. if(i % 2 != 0)
  39. result = result + power/factorial;
  40. else
  41. result = result - power/factorial;
  42.  
  43. printf("result is %.2f\n", result);
  44. }
  45. return result;
  46. }
  47.  
  48. /* Main Function Begins Here */
  49. int main()
  50. {
  51. int x;
  52. int steps;
  53. float result;
  54.  
  55. printf("Enter a series steps and X: ");
  56. scanf("%d %d", &steps, &x);
  57.  
  58. result = SumOfSeries(steps, x);
  59. printf("SumOfSeries is %.2f\n", result);
  60. }
  61.  
  62.  
Success #stdin #stdout 0s 9424KB
stdin
5
2
stdout
Enter a series steps and X: result is 2.00
result is 3.33
result is 3.60
SumOfSeries is 3.60