asin() Function Example in C Programming

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

asin() Function Overview

The asin() function in C is designed to determine the arcsine (or inverse sine) of a provided value. The result is given in radians and falls within the interval \([-π/2, π/2]\). 

The asin() function is a part of the math.h library. The function accepts one argument, which is the value whose arcsine is to be calculated, and should lie in the range [-1, 1]. 

Key Points: 

- Make sure to include the math.h header to access the asin() function. 

- The value provided to the function should be between -1 and 1, both inclusive. 

- The output will be in radians. If needed, convert the result to degrees using the formula: degree = radian × 180 / π

- When compiling, remember to link the math library using the -lm flag.

Source Code Example

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

int main() {
    double value, result_in_radians, result_in_degrees;

    // Obtain value from user for which arcsine is to be calculated
    printf("Enter a value between -1 and 1: ");
    scanf("%lf", &value);

    // Ensure the input value is within the permissible range
    if (value < -1 || value > 1) {
        printf("Error: The input value must lie in the range [-1, 1].\n");
        return 1;
    }

    // Calculate arcsine of the value
    result_in_radians = asin(value);

    // Convert result to degrees for convenience
    result_in_degrees = result_in_radians * 180.0 / M_PI;

    // Display the results
    printf("Arcsine of %.2lf in radians is: %.2lf\n", value, result_in_radians);
    printf("Arcsine of %.2lf in degrees is: %.2lf\n", value, result_in_degrees);

    return 0;
}

Output

Enter a value between -1 and 1: 0.5
Arcsine of 0.50 in radians is: 0.52
Arcsine of 0.50 in degrees is: 30.00

Explanation

1. We start by incorporating the necessary header files: stdio.h for I/O tasks and math.h to employ the asin() function.

2. In the main() function, we prompt the user to provide a value for which the arcsine is to be calculated.

3. We validate that the input lies within the interval [-1, 1]. If not, an error message is displayed, and the program exits.

4. The arcsine of the input value is then computed using the asin() function.

5. The result is also transformed to degrees for user-friendly representation.

6. Finally, both the radian and degree values are printed to the console.


Comments