An algorithm as a sequence of statements
A C program is a sequence: statements run one after another, top to bottom. Print the average algorithm step by step: after Hello, world! add an empty line and five new printf lines:
printf("\n");
printf("Algorithm: the average of grades\n");
printf("1. Add up all the grades.\n");
printf("2. Count how many grades there are.\n");
printf("3. Divide the sum by the count.\n");
printf("4. Print the answer.\n");
printf("\n"); prints only a new line, so an empty line appears in the output. Run it:
Hello, world!
Algorithm: the average of grades
1. Add up all the grades.
2. Count how many grades there are.
3. Divide the sum by the count.
4. Print the answer.
Swap two printf lines and run again: the steps are printed in the order they are written. Put them back and make a commit: Print steps in order.
Read the errors
You will see errors every day, and that is normal. What matters is reading them. Delete the semicolon after the first printf and click ▶. The build window opens at the bottom with the error:
C:/.../practice/01/main.c: In function 'main':
C:/.../practice/01/main.c:4:30: error: expected ';' before 'printf'
4 | printf("Hello, world!\n")
| ^
| ;
5 | printf("\n");
| ~~~~~~
An error line always has the same shape: file:line:column: error: what is wrong. Here: main.c, line 4, column 30, "expected ; before the next printf". GCC even draws where it is missing.
Put the ; back and write prinft instead of printf:
C:/.../practice/01/main.c:4:5: error: implicit declaration of function 'prinft'; did you mean 'printf'? [-Werror=implicit-function-declaration]
4 | prinft("Hello, world!\n");
| ^~~~~~
| printf
cc1.exe: all warnings being treated as errors
The compiler does not know a function called prinft and suggests printf. The last line says this was a warning, but -Werror turned it into an error.
Two rules:
- Fix the first error. One error often causes several more, which disappear when you fix the first.
- Read the whole line. The answer is often already there:
did you mean 'printf'?.
Put printf back and check that the program works again.