Operators and control flow
This lesson covers how C calculates and decides: arithmetic and comparison operators, if, switch, and the three loops. C's syntax here was copied by Java, JavaScript, C#, Go and many others, so it will look familiar everywhere.
Arithmetic
#include <stdio.h>
int main(void) {
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("-17 / 5 = %d, -17 %% 5 = %d\n", -17 / 5, -17 % 5);
int n = 10;
n += 5; printf("n += 5 → %d\n", n);
n *= 2; printf("n *= 2 → %d\n", n);
n++; printf("n++ → %d\n", n);
return 0;
}17 + 5 = 22 17 - 5 = 12 17 * 5 = 85 17 / 5 = 3 17 % 5 = 2 -17 / 5 = -3, -17 % 5 = -2 n += 5 → 15 n *= 2 → 30 n++ → 31
/between integers drops the remainder (toward zero);%gives the remainder.x += 5is short forx = x + 5, and the same works for-=,*=,/=,%=.n++and++nboth add one. As a statement on its own they're the same; inside a bigger expressionn++gives the old value. Keep them on their own line and you'll never need to remember the difference.
Comparison and logic
Comparisons produce 1 (true) or 0 (false). In conditions, any non-zero value is true:
#include <stdio.h>
int main(void) {
int age = 20, has_ticket = 1;
printf("age >= 18: %d\n", age >= 18);
printf("age == 21: %d\n", age == 21);
printf("adult and ticket: %d\n", age >= 18 && has_ticket);
printf("child or no ticket: %d\n", age < 12 || !has_ticket);
if (42) printf("42 counts as true\n");
if (!0) printf("!0 is true\n");
return 0;
}age >= 18: 1 age == 21: 0 adult and ticket: 1 child or no ticket: 0 42 counts as true !0 is true
| Operator | Meaning |
|---|---|
== != |
Equal, not equal |
< <= > >= |
Less / greater |
&& |
And (stops early if the left side is false) |
|| |
Or (stops early if the left side is true) |
! |
Not |
⚠️
if (x = 5)assigns 5 toxand is always true. You meant==. With-Wall, GCC warns: "suggest parentheses around assignment used as truth value".
if / else
#include <stdio.h>
int main(void) {
int scores[] = {95, 72, 58, 81};
for (int i = 0; i < 4; i++) {
int s = scores[i];
char grade;
if (s >= 90) {
grade = 'A';
} else if (s >= 75) {
grade = 'B';
} else if (s >= 60) {
grade = 'C';
} else {
grade = 'F';
}
printf("%d → %c\n", s, grade);
}
return 0;
}95 → A 72 → C 58 → F 81 → B
The braces are optional for a single statement, but always use them. Apple's famous 2014 "goto fail" SSL bug came from a missing pair of braces.
The ternary operator
condition ? a : b picks a value:
#include <stdio.h>
int main(void) {
int items = 1;
printf("%d item%s\n", items, items == 1 ? "" : "s");
items = 3;
printf("%d item%s\n", items, items == 1 ? "" : "s");
int a = 8, b = 13;
int max = a > b ? a : b;
printf("max = %d\n", max);
return 0;
}1 item 3 items max = 13
switch
switch compares one integer value against fixed cases:
#include <stdio.h>
int main(void) {
char commands[] = {'s', 'q', 'h', '?', 'x'};
for (int i = 0; i < 5; i++) {
switch (commands[i]) {
case 's':
printf("start\n");
break;
case 'q':
case 'x':
printf("quit\n");
break;
case 'h':
case '?':
printf("help\n");
break;
default:
printf("unknown command\n");
}
}
return 0;
}start quit help help quit
Every case needs a break; without it, execution "falls through" into the next case. Stacking case 'q': case 'x': on purpose shares one block. default handles everything else. switch only works with integers and characters, not strings.
Loops
for
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 5; i++) {
printf("%d ", i * i);
}
printf("\n");
for (int i = 10; i > 0; i -= 3) printf("%d ", i);
printf("\n");
return 0;
}1 4 9 16 25 10 7 4 1
for (start; condition; step): run start once, then repeat the body while condition is true, running step after each round.
while and do … while
#include <stdio.h>
int main(void) {
// while: check first
int n = 27, steps = 0;
while (n != 1) {
n = (n % 2 == 0) ? n / 2 : 3 * n + 1;
steps++;
}
printf("27 reaches 1 in %d steps\n", steps);
// do-while: run at least once, check after
int tries = 0;
do {
tries++;
printf("try %d\n", tries);
} while (tries < 3);
return 0;
}27 reaches 1 in 111 steps try 1 try 2 try 3
do … while is perfect for "ask until the input is valid", because you need to ask at least once.
break and continue
#include <stdio.h>
int main(void) {
int numbers[] = {4, 7, -1, 12, 0, 9};
int sum = 0;
for (int i = 0; i < 6; i++) {
if (numbers[i] < 0) continue; // skip negatives
if (numbers[i] == 0) break; // 0 means "end of data"
sum += numbers[i];
}
printf("sum = %d\n", sum);
return 0;
}sum = 23
Nested loops
#include <stdio.h>
int main(void) {
for (int row = 1; row <= 4; row++) {
for (int col = 1; col <= 4; col++) {
printf("%4d", row * col);
}
printf("\n");
}
return 0;
}1 2 3 4 2 4 6 8 3 6 9 12 4 8 12 16
break only leaves the innermost loop. To leave several at once, put the loops in a function and return, or use a flag variable.
Reading input with scanf
#include <stdio.h>
int main(void) {
int count;
printf("How many numbers? ");
if (scanf("%d", &count) != 1 || count < 0) {
printf("That's not a valid count\n");
return 1;
}
long total = 0;
for (int i = 1; i <= count; i++) {
int x;
printf("Number %d: ", i);
if (scanf("%d", &x) != 1) {
printf("Not a number\n");
return 1;
}
total += x;
}
printf("Total: %ld\n", total);
return 0;
}./sumHow many numbers? 3 Number 1: 10 Number 2: 20 Number 3: 12 Total: 42
- The
&in&countpasses the variable's address, soscanfcan store into it (more on that in Pointers). scanfreturns how many values it read. Always check it: if the user typesabc, nothing is read andcountstays uninitialised.
./sumHow many numbers? abc That's not a valid count
Practice
- Print the numbers 1 to 100, but
Fizzfor multiples of 3,Buzzfor multiples of 5, andFizzBuzzfor both. - Ask for a number and print whether it's prime (try dividing by every number up to its square root).
- Use
switchto print the name of a day from its number (1 = Monday). - Print a triangle of
*with nested loops, 5 rows high.
1.What does 17 % 5 give?
2.What happens if you forget break in a switch case?
3.What's wrong with if (x = 0) { … }?
4.Which loop always runs its body at least once?