Computing Trigonometric Series: C Program for Cosine Calculation

Write a Program to find Sin s series 1-x2/2! + x4/4! - x6/6! + x8/8! - .....

In this programming journey, we delve into a C program designed to calculate the cosine of an angle using a series expansion. The code utilizes a loop and mathematical operations to approximate the value of cos(x). Let's dissect the code to understand how it achieves this computation.

The Code:


 #include <stdio.h>
 main()
  {
    int i = 1, n, y;
    float sum, t, x;
    printf("Enter the number of terms and degree : ");
    scanf("%d %f", &n, &y);
    x = y * 3.142 / 180;
    sum = 1;
    t = 1;
    while( i < n)
     {
       t = ((-t) * x * x) / ((2 * i) * (2 * i - 1));
       sum = sum + t;
       i++;
     }
    printf(" The value of Cos(%d) is %f ", y, sum);
  }

Explanation:

  1. User Input:

    The program prompts the user to enter the number of terms and the degree for which the cosine value needs to be calculated.

  2. Conversion to Radians:

    The input degree (y) is converted to radians (x) using the formula x = y * 3.142 / 180.

  3. Series Computation:

    The program utilizes a loop to compute the cosine series. It updates the term (t) and accumulates the sum based on the specified number of terms (n).

  4. Output:

    The final result is printed, representing the approximate value of cos(x) for the given degree.

Input and Output Example:

Assuming the user enters 10 terms and 60 degrees:

  • Input: Enter the number of terms and degree: 10 60
  • Output: The value of Cos(60) is 0.49999

This indicates that the program has approximated the cosine of 60 degrees using a series expansion, providing an output of approximately 0.49999.

Conclusion:

Exploring mathematical series expansions in programming enhances our understanding of numerical approximations. This C program offers a glimpse into calculating cosine values through a series approach. Feel free to experiment with different inputs to observe how the program handles various scenarios. Happy coding!

Post a Comment

0 Comments