C in 100 Seconds: Arithmetic Operators | Episode 4
Video: C in 100 Seconds: Arithmetic Operators | Episode 4 by Taught by Celeste AI - AI Coding Coach
Watch full page →Arithmetic Operators — Math in C
C in 100 Seconds, Episode 4
C gives you five arithmetic operators. Four of them work exactly like you'd expect. The fifth one has a catch.
The Five Operators
int a = 17, b = 5;
a + b // 22 — addition
a - b // 12 — subtraction
a * b // 85 — multiplication
a / b // 3 — division (integer!)
a % b // 2 — modulus (remainder)
Addition, subtraction, and multiplication do what you'd expect. Modulus gives you the remainder after division. But division? That's where it gets interesting.
The Integer Division Gotcha
When you divide two integers, C throws away the decimal part:
17 / 5 // 3, not 3.4
The result is truncated, not rounded. C doesn't promote the result to a float — it stays as an integer because both operands are integers.
To get the decimal result, make at least one operand a float:
17.0 / 5 // 3.4
That .0 changes everything. Now C performs floating-point division instead.
Why Does This Matter?
Integer division is one of the most common sources of bugs in C. Calculate an average with sum / count where both are int, and you'll get a truncated result with no warning. C trusts you to know the difference.
Full Code
#include <stdio.h>
int main() {
int a = 17, b = 5;
printf("%d + %d = %d\n", a, b, a + b);
printf("%d - %d = %d\n", a, b, a - b);
printf("%d * %d = %d\n", a, b, a * b);
printf("%d / %d = %d\n", a, b, a / b);
printf("%d %% %d = %d\n", a, b, a % b);
printf("\n17 / 5 = %d (integer division truncates)\n", 17 / 5);
printf("17.0 / 5 = %.1f (use float for decimals)\n", 17.0 / 5);
return 0;
}
Compile and Run
gcc arithmetic.c -o arithmetic
./arithmetic
Next episode: If/Else — making decisions in your code.
Student code: github.com/GoCelesteAI/c-in-100-seconds/episode04