Math
Lesson 9Author : Afrixi
Last Updated : January, 2023
Mathematical operations in C can be performed using arithmetic operators. Here are the arithmetic operators in C:
+
: Addition-
: Subtraction*
: Multiplication/
: Division%
: Modulo (remainder after division) Here are some examples:
#include <stdio.h>
int main() {
int a = 10, b = 20, c;
float x = 3.14, y = 2.5, z;
c = a + b;
printf("a + b = %d\n", c);
c = a - b;
printf("a - b = %d\n", c);
c = a * b;
printf("a * b = %d\n", c);
z = x / y;
printf("x / y = %f\n", z);
c = b % a;
printf("b %% a = %d\n", c);
return 0;
}
Output:
a + b = 30
a - b = -10
a * b = 200
x / y = 1.256000
b % a = 0
In the above example, we have performed arithmetic operations on integers and floating-point numbers using different arithmetic operators. Note that the modulus operator % returns the remainder after division.
In addition to arithmetic operators, C provides math functions that can perform more complex mathematical operations. Some of these functions are:
sqrt(x)
: Returns the square root ofx
.pow(x, y)
: Returns x raised to the power ofy
.sin(x)
,cos(x)
,tan(x)
: Returns the sine, cosine, and tangent ofx
, respectively.log(x)
,log10(x)
: Returns the natural logarithm and base-10 logarithm ofx
, respectively. Here’s an example that demonstrates the usage ofsqrt()
andpow()
functions:
#include <stdio.h>
#include <math.h>
int main() {
float x = 25, y = 3;
printf("sqrt(%f) = %f\n", x, sqrt(x));
printf("%f ^ %f = %f\n", x, y, pow(x, y));
return 0;
}
Output:
sqrt(25.000000) = 5.000000
25.000000 ^ 3.000000 = 15625.000000
In the above example, we have included the math.h header file to use the sqrt()
and pow()
functions.