BETA Try the new lesson view
Code

How long a lecture lasts

First, a program of the kind you can already write: everything in one main.c. It works out how long a lecture lasts from its start and end times.

Create practice/07:

add_executable(p07_duration main.c)
target_link_libraries(p07_duration PRIVATE course_input)

main.c. A time is kept as one number, minutes since midnight: 10:15 is 615. Then the duration is a plain subtraction.

  • int is_time(int hour, int min) – whether it's a real time of day. It returns the value of the condition: 1 or 0.
  • int to_minutes(int hour, int min) – hour * 60 + min. Precondition: the time is real.
  • int read_time(void) – asks for the hour and minutes until the time is real.
  • void print_time(int minutes) – prints HH:MM. %02d is an integer in 2 characters, padded with a zero in front: 9 becomes 09.
  • void print_duration(int minutes) – 90 min (1 h 30 min).
  • main asks for the start and the end and checks that the end is later.

Run it

p07_duration and ▶. Enter 10, 15, 11, 45:

Start
Hour: 10
Minutes: 15
End
Hour: 11
Minutes: 45
Lecture 10:15-11:45, duration 90 min (1 h 30 min)

Five functions and main already make almost 70 lines. The time functions would suit another program too, e.g. a lecture timetable, but you can't take them out of main.c. In the next step you move them into a module.

Commit: Compute lecture length.