Your First Program: printf

Hello, World!

By tradition, the first program in a new language prints Hello, World!. Here it is in C:

#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}

Output

Hello, World!

That's a complete C program! We will look at every line in the next lesson. For now, focus on the middle line:

printf("Hello, World!\n"); prints the text inside the double quotes. printf is said "print-eff" (print formatted).

Printing more lines

You can call printf as many times as you like. The lines run from top to bottom:

#include <stdio.h>

int main() {
    printf("My name is Asha.\n");
    printf("I am learning C.\n");
    printf("This is fun!\n");
    return 0;
}

Output

My name is Asha.
I am learning C.
This is fun!

What is \n?

\n means new line. It moves the cursor down to the start of the next line. printf does not do this by itself. See what happens without it:

#include <stdio.h>

int main() {
    printf("Hello");
    printf("World");
    printf("\n");
    return 0;
}

Output

HelloWorld

Both words end up on the same line, stuck together. You can also put \n in the middle of the text:

#include <stdio.h>

int main() {
    printf("Line one\nLine two\nLine three\n");
    return 0;
}

Output

Line one
Line two
Line three

Other special characters

A backslash \ starts a special character (an escape sequence):

WriteTo get
\nA new line
\tA tab (a big space, good for lining things up)
\"A double quote inside the text
\\One backslash
#include <stdio.h>

int main() {
    printf("Name:\tAsha\n");
    printf("She said \"hi!\"\n");
    printf("A backslash: \\\n");
    return 0;
}

Output

Name:	Asha
She said "hi!"
A backslash: \

Every statement ends with ;

In C, every instruction (a statement) ends with a semicolon ;. It is like the full stop at the end of a sentence. Forget it, and the program won't compile:

#include <stdio.h>

int main() {
    printf("Hello\n")
    return 0;
}

Output (the program does not compile)

    return 0;
    ^
main.c:5: error: ';' expected

The message says a ; was expected. The compiler noticed the problem when it reached the next line.

Common mistake: Forgetting the ; is the most common beginner error in C. When you see an error, first check the line it points at, and the line just before it.

HOME LABS COMMUNITY DASHBOARD