cos() Function
The cos() function in C computes the cosine of an angle provided in radians and returns the result as a double. It is widely used in mathematical computations and applications where trigonometric calculations are required.
Syntax of cos()
</>
                        Copy
                        double cos(double x);Parameters
| Parameter | Description | 
|---|---|
| x | An angle expressed in radians. (Note: One radian is equivalent to 180/PI degrees.) | 
The function computes the cosine of the given angle using floating-point arithmetic. Ensure that the angle is provided in radians for correct results.
Examples for cos()
Example 1: Calculating the Cosine of 0 Radians
This example demonstrates the use of cos() to compute the cosine of an angle equal to 0 radians.
Program
</>
                        Copy
                        #include <stdio.h>
#include <math.h>
int main() {
    double result = cos(0.0);
    printf("cos(0) = %f\n", result);
    return 0;
}Explanation:
- The program includes the necessary headers <stdio.h>and<math.h>.
- The cos()function is called with an argument of 0.0 radians.
- The result, which is the cosine of 0 radians, is stored in the variable result.
- The output is printed using printf().
Program Output:
cos(0) = 1.000000Example 2: Evaluating the Cosine of PI/3 Radians
This example demonstrates how to compute the cosine of an angle equal to PI/3 radians.
Program
</>
                        Copy
                        #include <stdio.h>
#include <math.h>
#define PI 3.141592653589793
int main() {
    double angle = PI / 3;
    double result = cos(angle);
    printf("cos(PI/3) = %f\n", result);
    return 0;
}Explanation:
- The constant PIis defined for accurate computation.
- The angle is computed as PI/3radians.
- The cos()function calculates the cosine ofPI/3radians.
- The result is printed to the console using printf().
Program Output:
cos(PI/3) = 0.500000Example 3: Computing Cosine Values for Multiple Angles
This example demonstrates how to compute and display the cosine values for an array of angles expressed in radians.
Program
</>
                        Copy
                        #include <stdio.h>
#include <math.h>
#define PI 3.141592653589793
int main() {
    double angles[] = {0, PI/4, PI/2, PI};
    int n = sizeof(angles) / sizeof(angles[0]);
    
    for (int i = 0; i < n; i++) {
        printf("cos(%f) = %f\n", angles[i], cos(angles[i]));
    }
    
    return 0;
}Explanation:
- An array of angles in radians is defined.
- The program calculates the number of elements in the array.
- A loop iterates through each angle, computes its cosine using cos(), and prints the result.
Program Output:
cos(0.000000) = 1.000000
cos(0.785398) = 0.707107
cos(1.570796) = 0.000000
cos(3.141593) = -1.000000