Operators & Expressions
int a = 10, b = 3;
printf("%d\n", a + b); // 13
printf("%d\n", a - b); // 7
printf("%d\n", a * b); // 30
printf("%d\n", a / b); // 3 (integer division truncates!)
printf("%d\n", a % b); // 1 remainder
Note that dividing two int values always produces an int result, discarding any decimal part. To get a decimal answer, at least one operand must be a float or double.
int x = 5, y = 10;
printf("%d\n", x == y); // 0 (false)
printf("%d\n", x != y); // 1 (true)
printf("%d\n", x < y && y > 0); // 1 (true) - both conditions true
printf("%d\n", x > y || y > 0); // 1 (true) - at least one condition true
C has no true boolean type in its original form — comparisons simply evaluate to the integer 1 (true) or 0 (false), which you can store directly in an int.
int count = 5;
count++; // same as count = count + 1 (now 6)
count--; // same as count = count - 1 (back to 5)
count += 10; // same as count = count + 10 (now 15)
count *= 2; // same as count = count * 2 (now 30)
These shortcuts appear constantly in C code, especially inside loops, so getting comfortable reading them quickly is essential.
++count (pre-increment) increases the value before it's used in an expression. count++ (post-increment) uses the current value first, then increases it afterward:
int a = 5;
printf("%d\n", ++a); // prints 6 (incremented first)
int b = 5;
printf("%d\n", b++); // prints 5 (uses old value, then becomes 6)
7 / 2 in C evaluates to 3, not 3.5, because both operands are integers. To get a decimal result, cast at least one value: (float)7 / 2 correctly gives 3.5.
Write a program that calculates both the integer quotient and the true decimal result of dividing two numbers, to see the difference clearly.
#include <stdio.h>
int main() {
int a = 17, b = 5;
printf("Integer division: %d\n", a / b);
printf("Decimal division: %.2f\n", (float)a / b);
return 0;
}