C Tutorial menu

C Operators

Operators perform actions on values, like adding, comparing or combining them.

Arithmetic Operators

OperatorMeaningExampleResult
+Add10 + 414
-Subtract10 - 46
*Multiply10 * 440
/Divide10 / 42
%Remainder10 % 42
++Add 1x++
--Subtract 1x--

Example

c
#include <stdio.h>

int main(void) {
  int minutes = 135;
  int hours = minutes / 60;
  int left = minutes % 60;
  printf("%d hours and %d minutes\n", hours, left);
  return 0;
}
Output
2 hours and 15 minutes

% only works with whole numbers. A common use is checking if a number is even: n % 2 == 0.

Assignment Operators

OperatorSame as
x += 5x = x + 5
x -= 5x = x - 5
x *= 5x = x * 5
x /= 5x = x / 5
x %= 5x = x % 5

Example

c
#include <stdio.h>

int main(void) {
  int stock = 50;
  stock -= 12;   // sold 12
  stock += 30;   // new delivery
  stock++;       // one returned
  printf("Stock: %d\n", stock);
  return 0;
}
Output
Stock: 69

Comparison Operators

In C, a comparison gives 1 for true and 0 for false.

OperatorMeaning
==Equal to
!=Not equal to
> / <Greater / less than
>= / <=Greater or equal / less or equal

Example

c
#include <stdio.h>

int main(void) {
  int a = 8, b = 3;
  printf("%d\n", a > b);
  printf("%d\n", a == b);
  return 0;
}
Output
1
0

Logical Operators

  • && (and): true when both conditions are true
  • || (or): true when at least one is true
  • ! (not): reverses the result

Example

c
int age = 22;
int hasTicket = 1;
printf("%d\n", age >= 18 && hasTicket);   // prints 1
printf("%d\n", !hasTicket);               // prints 0

The sizeof Operator

sizeof tells you how many bytes a type or variable uses in memory:

Example

c
#include <stdio.h>

int main(void) {
  printf("int: %zu bytes\n", sizeof(int));
  printf("char: %zu byte\n", sizeof(char));
  return 0;
}
Output
int: 4 bytes
char: 1 byte

The size of int can be different on some systems, but 4 bytes is the usual value on modern computers.

Exercise

Exercise

What is the value of 23 % 4 in C?

Learn C with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp