C course menu
Your First C Program: Hello World Explained Line by Line
Write, compile and run your first C program, and understand every line: #include, the main function, printf, escape sequences such as \n, return 0, and how to read your first compiler errors.
On this page
Programmers traditionally start a new language by printing "Hello, World!". Let us write it and then understand every line.
The program#
#include <stdio.h>
int main(void) {
printf("Hello, World!\n");
return 0;
}Hello, World!Compile and run it as shown in Installing a C Compiler:
gcc -std=c17 -Wall -Wextra hello.c -o hello
./helloLine by line#
Escape sequences#
\n inside a string is a new line. Without it, the next output continues on the same line. A backslash starts an escape sequence:
printf("Line one\nLine two\n");
printf("Name:\tAsha\n");
printf("She said \"hi\"\n");
printf("Path: C:\\temp\n");Line one
Line two
Name: Asha
She said "hi"
Path: C:\tempSeveral statements#
Statements run one after another, from top to bottom:
printf("Step 1: boil water\n");
printf("Step 2: add tea leaves\n");
printf("Step 3: add milk and sugar\n");Step 1: boil water
Step 2: add tea leaves
Step 3: add milk and sugarPrinting numbers#
printf uses format specifiers such as %d to insert values into the text:
printf("%d apples cost %d rupees\n", 3, 3 * 30);
printf("Total items: %d\n", 3 + 4);3 apples cost 90 rupees
Total items: 7%d prints an int. You will learn the other specifiers in Input and Output.
Your first errors#
Mistakes are normal. The compiler reports them with the file name, line and column.
Forgetting a semicolon:
#include <stdio.h>
int main(void) {
printf("Hello")
return 0;
}GCC reports something like error: expected ';' before 'return', pointing at the line after the missing semicolon.
Forgetting #include <stdio.h> gives a warning or error about an implicit declaration of printf. Read the first message carefully; later messages are often caused by the first one.
Practice#
Practice exercise
Write a program that prints this exact output, using one printf with \n and \t, and calculating 12 × 4 in the code:
Item Qty Total
Pen 12 48Show solution
#include <stdio.h>
int main(void) {
printf("Item\tQty\tTotal\nPen\t%d\t%d\n", 12, 12 * 4);
return 0;
}Item Qty Total
Pen 12 48Key takeaway#
Finished this lesson?