Learn C · lesson 24 of 60 · about 10 minutes
Project: Temperature Table
End the report with a table of CPU temperatures, built from small functions that each do one job, and say how this machine's temperature compares.
What you'll learn
- Split a task into functions
- Loop and call functions
- Format a table with widths
A table for the CPU
The report already reads the CPU temperature and calls it warm or too hot. A table makes those limits easy to see: 40, 60, 80 and 100 °C, each in Fahrenheit too, with the word the report would use. The last line says what this machine's own temperature counts as. Every part is a small function with one job, and main only loops and calls.
Small functions, one job each
to_fahrenheit(c)does the mathscpu_status(c)picks a word for the temperature, catching sensor errors firstprint_row(c)prints one line of the tablemainloops from 40 to 100 in steps of 20
The table
#include <stdio.h>
// a CPU temperature in Fahrenheit
double to_fahrenheit(int c) {
return c * 9.0 / 5.0 + 32.0;
}
// a word for a CPU temperature, with the same limits as the report
const char *cpu_status(int c) {
if (c < 0 || c > 120) return "sensor error";
if (c >= 85) return "too hot";
if (c >= 60) return "warm";
return "ok";
}
// one row of the temperature table
void print_row(int c) {
printf("%6d | %6.1f | %s\n", c, to_fahrenheit(c), cpu_status(c));
}
int main(void) {
printf(" CPU C | CPU F | status\n");
for (int c = 40; c <= 100; c += 20) {
print_row(c);
}
return 0;
}Output
CPU C | CPU F | status
40 | 104.0 | ok
60 | 140.0 | warm
80 | 176.0 | warm
100 | 212.0 | too hotTip
%6.1f pads the number to 6 characters with 1 decimal place, so the columns line up however long the numbers are.
Now try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.