Labs ICT
โญ Pro Login

Arithmetic Operators

Arithmetic is the most basic thing you will do in C. Addition, subtraction, multiplication, division โ€” the stuff you learned in elementary school. C has an operator for all of them, plus a few more.

The Basic Operators

  • + โ€” addition
  • - โ€” subtraction
  • * โ€” multiplication
  • / โ€” division
  • % โ€” modulus (remainder of division)

Modulus is the odd one out. It gives you the remainder after division. 7 % 3 is 1, because 3 goes into 7 twice, with 1 leftover. It is incredibly useful for checking if a number is even (n % 2 == 0) or for cycling through ranges.

Increment and Decrement

++ adds 1 to a variable. -- subtracts 1. They look strange but are extremely common in C.

There are two flavors:

  • Prefix (++x) โ€” increments first, then returns the new value
  • Postfix (x++) โ€” returns the current value, then increments

This distinction matters when you use them inside larger expressions.


#include 

int main() {
  int a = 10, b = 3;

  printf("a + b = %d\n", a + b);
  printf("a - b = %d\n", a - b);
  printf("a * b = %d\n", a * b);
  printf("a / b = %d\n", a / b);
  printf("a %% b = %d\n", a % b);

  int x = 5;
  printf("Prefix ++x: %d\n", ++x);
  printf("After prefix, x: %d\n", x);

  int y = 5;
  printf("Postfix y++: %d\n", y++);
  printf("After postfix, y: %d\n", y);

  return 0;
}
    
Try it Yourself โ†’

๐Ÿงช Quick Quiz

What does the % operator do in C?