C Get Started
To run a C program, two steps are needed. First a compiler translates the C source code, which people can read, into a program the computer can run. Then you run that program. On your own computer you would install a compiler such as GCC or Clang; in this tutorial the online editor does both steps for you.
Your first program
#include <stdio.h>
int main(void) {
printf("Hello, World!\n");
return 0;
}Hello, World!
Let us read it line by line.
#include <stdio.h>brings in the standard input and output library.printf, which prints text, is declared there. Without this line the compiler does not knowprintf.int main(void)starts the main function. Every C program has exactly onemain, and the program starts running at its first line.intmeansmaingives back a whole number when it ends;voidmeans it takes no inputs.- The curly braces
{and}mark the start and the end ofmain's body. printf("Hello, World!\n");prints the text between the double quotes.\nis a newline: it moves the cursor to the next line.return 0;endsmainand tells the system the program finished without problems.- Every statement ends with a semicolon
;.
Compiling and running in the terminal
When you press Run in the editor, it types two commands into the terminal for you:
gcc -Wall main.c -o main && ./main
gcc -Wall main.c -o main compiles main.c into a program called main; -Wall asks for warnings about suspicious code, which helps you find mistakes early. ./main runs the program. The && means "run the second command only if the first one worked", so a program with errors is not run.
When something goes wrong
Mistakes are normal. If you forget the semicolon after printf(...), the compiler stops and prints the file name, the line, the column and what it expected, for example expected ';' after expression. The editor also adds a short hint. Fix the line and run again.
A program can print several lines with several printf calls, or with several \n in one call:
#include <stdio.h>
int main(void) {
printf("Learning C\n");
printf("is fun.\n");
printf("One\nTwo\nThree\n");
return 0;
}Learning C is fun. One Two Three
Practice exercises
- Print your name on one line and your age on the next, with two
printfcalls. - Print the same two lines with a single
printfcall. - Print a small box made of
*characters over three lines. - Remove
#include <stdio.h>, run the program and read the message. Then put the line back.