C Maths

In the C programming language, the "C math" refers to a collection of mathematical functions provided by the standard C library to perform various mathematical operations. These functions are included in the <math.h> header file and can be used for tasks such as basic arithmetic operations, trigonometric calculations, logarithmic computations, and more.

1. Basic Arithmetic Functions:

a. double pow(double base, double exponent):
- This function calculates the value of base raised to the power of exponent.

        
#include <stdio.h>
#include <math.h>

int main() {
    double result = pow(2, 3); // 2^3 = 8
    printf("2^3 = %.2f\n", result);
    return 0;
}
        
    

b. double sqrt(double x):
- Computes the square root of the given number x.

        
#include <stdio.h>
#include <math.h>

int main() {
    double root = sqrt(16); // Square root of 16 = 4.0
    printf("Square root of 16 = %.2f\n", root);
    return 0;
}
        
    

2. Trigonometric Functions:

C provides trigonometric functions like sin, cos, and tan for working with angles. These functions take angles in radians.

        
#include <stdio.h>
#include <math.h>

int main() {
    double angle = M_PI / 4; // 45 degrees in radians
    double sin_val = sin(angle);
    double cos_val = cos(angle);
    double tan_val = tan(angle);

    printf("sin(45 degrees) = %.2f\n", sin_val);
    printf("cos(45 degrees) = %.2f\n", cos_val);
    printf("tan(45 degrees) = %.2f\n", tan_val);
    
    return 0;
}
        
    

3. Logarithmic Functions:

a. double log(double x):
- Computes the natural logarithm (base e) of the given number x.

        
#include <stdio.h>
#include <math.h>

int main() {
    double value = 2.71828; // e
    double log_val = log(value); // Natural logarithm of e is 1.0
    printf("ln(e) = %.2f\n", log_val);
    return 0;
}
        
    

4. Other Common Functions:

C math library also includes functions for rounding (ceil, floor, round), absolute value (fabs), and more.

        
#include <stdio.h>
#include <math.h>

int main() {
    double num = -4.5;
    double absolute_val = fabs(num); // Absolute value of -4.5 = 4.5
    double rounded_up = ceil(num);   // Round up to the nearest integer
    double rounded_down = floor(num); // Round down to the nearest integer

    printf("Absolute value of -4.5 = %.2f\n", absolute_val);
    printf("Ceiling of -4.5 = %.2f\n", rounded_up);
    printf("Floor of -4.5 = %.2f\n", rounded_down);
    
    return 0;
}