C — Programming fundamentals
A C program evaluates expressions in statements. Give each intermediate result a name so its value and its unit are easy to trace.
A simple example
Follow one calculation
- Start with 2 and 3
- Do this Add, then print
- Result 5
#include <stdio.h>
int main(void) {
printf("%d\n", 2 + 3);
}
5
Trace an elapsed-time calculation
Use a nonnegative duration in whole minutes as input. Divide it into complete hours and leftover minutes, then print the two results with their units. For these nonnegative int operands, / gives the whole-hour quotient and % gives the remainder. printf formats both integers for display.
A travel app records a bus journey as 134 minutes. Divide by 60 to find the full hours, then keep the remaining minutes for a timetable a passenger can read.
Run the example
Use a C17 compiler. Run these commands from the directory containing the example. Use a Unix-style shell.
cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lesson
#include <stdio.h>
int main(void) {
int elapsed = 134;
int hours = elapsed / 60;
int minutes = elapsed % 60;
printf("%d h %d min\n", hours, minutes);
return 0;
}
2 h 14 min
For 134 minutes, two full hours account for 120 minutes and leave 14. Multiplying the hours by 60 and adding the remainder reconstructs the input.
Try it yourself
What should the program print at exactly 60 minutes?
Check your answer
It prints 1 h 0 min. An exact multiple of 60 has no leftover minutes.