fork download
  1. /* Program to find sum of series: 1 + x2/!2 + x4/!4 + x6/!6 ………… ( Cos 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. float power;
  32. float factorial;
  33. int i, j;
  34.  
  35. /* here i will be used to run loop 5 times to get 5 elements and j is used to match the pattern 1+2 for each element in series */
  36. for(int i = 1, j = 0; i <= steps; i++, j = j+2)
  37. {
  38. power = xpower(j, x);
  39. factorial = xfactorial(j);
  40.  
  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. /* Pending */
Success #stdin #stdout 0s 9424KB
stdin
5
2
stdout
Enter a series steps and X: result is 1.00
result is 3.00
result is 3.67
result is 3.76
result is 3.76
SumOfSeries is 3.76