Skip to main content

Calculation

Introductionโ€‹

C provides different ways to do arithmetic calculations. These operators are built-in functions of the C language. Real-life operations like addition, subtractions, multiplication are used in the programs for calculation.

Operatorsโ€‹

Operators are symbols that are used in expressions or during logical computations. There are 3 types of arithmetic operators.

  • Unary operators - These operate on an operand or variable E.g: ++,- -
  • Binary operators - These work on two operands E.g: +, -, *, %, <, <=, !=, &&, =+, =-, %=
  • Ternary operators - This works for if-else conditions. E.g: ? :
note

The == operator checks whether a is equal to b. However, the !={" "} operator checks whether a is not equal to b. Therefore, they are called binary operators since they either return true or false.

Additionโ€‹

Addition operator can be used to add multiple numbers in C. + operator is used to add the numbers.

// Adding two numbers

#include <stdio.h>

int main() {

// Defining two variables
int num1 = 7;
int num2 = 4;

// Defining result variable
int result = num1 + num2;

printf("%d", result);

return 0;
}

Output:

11

Subtractionโ€‹

Subtraction operator - is used for subtraction operation.

// Subtracting two numbers

#include <stdio.h>

int main() {

// Defining two variables
int num1 = 7;
int num2 = 4;

// Defining result variable
int result = num1 - num2;

printf("%d", result);

return 0;
}

Output:

3

Multiplicationโ€‹

Multiplication is done using the * operator.

// Multiplying two numbers

#include <stdio.h>

int main() {

// Defining two variables
int num1 = 7;
int num2 = 4;

// Defining result variable
int result = num1 * num2;

printf("%d", result);

return 0;
}

Output:

28

Divisionโ€‹

Division operator / is used for division operations.

// Dividing two numbers

#include <stdio.h>

int main() {

// Defining two variables
int num1 = 10;
int num2 = 2;

// Defining result variable
int result = num1 / num2;

printf("%d", result);

return 0;
}

Output:

5

Exponentโ€‹

The pow(x, y) function returns, x raised to the power of y. You require including <math.h> header file for the exponent operation.

// Calculating exponent

#include <stdio.h>

// Another library which has the exponent function
#include <math.h>

int main() {

// Defining two variables
int num1 = 2;
int num2 = 3;

// Defining result variable using the pow(num, exponent) function
int result = pow(num1, num2);

printf("%d", result);

return 0;
}

Output:

8