cos() Function Example in C Programming

In this source code example, we will see how to use the cos() function in C programming with an example.

cos() Function Overview

The cos() function in C is utilized to compute the cosine of a provided angle in radians. It is located within the math.h library. The function receives one argument—the angle in radians—and yields the cosine value of this angle. 

Key Points: 

- The function mandates the inclusion of the math.h header. 

- The argument must be presented in radians. To transform degrees into radians, employ the equation: radian = degree × π / 180

- Always link the math library when compiling with the -lm flag.

Source Code Example

#include <stdio.h>
#include <math.h>  // Necessary for cos()

int main() {
    double angle_in_degrees, angle_in_radians, result;

    // Receive angle in degrees
    printf("Enter angle in degrees: ");
    scanf("%lf", &angle_in_degrees);

    // Transition degrees to radians
    angle_in_radians = angle_in_degrees * M_PI / 180.0;

    // Calculate the cosine value
    result = cos(angle_in_radians);

    // Showcase the outcome
    printf("Cosine value of %.2lf degrees is: %.2lf\n", angle_in_degrees, result);

    return 0;
}

Output

Enter angle in degrees: 60
Cosine value of 60.00 degrees is: 0.50

Explanation

1. We commence by including the essential header files: stdio.h for input/output operations and math.h for mathematical functions, encompassing cos().

2. In our main() function, we solicit an input for an angle in degrees.

3. This angle undergoes a conversion from degrees to radians using the equation: radian = degree × π / 180. Notably, the constant M_PI in C is delineated in math.h, symbolizing π's value.

4. We then invoke the cos() function, furnishing the radian value as its argument, to procure the cosine value.

5. In the end, we exhibit the result on the console.


Comments