CodeMIRAI
0 XP

Your first program

2 min read 4 runnable examples Quiz included
C
#include <stdio.h>

int main() {
    printf("Hello, world!\n");
    printf("I am learning C.\n");
    return 0;
}

Line by line

#include <stdio.h> brings in the standard input/output library, which provides printf. Lines starting with # are instructions to the preprocessor, which runs before compilation.

int main() { ... } defines the main function. Every C program starts running at main. The int says the function returns a whole number to the operating system.

printf("..."); prints text. \n is a new line; without it, the next output continues on the same line.

Semicolons end statements. Forgetting one is the most common C error.

return 0; ends main and tells the operating system the program succeeded. A non-zero value signals an error.

Curly braces and indentation

Curly braces { } group statements into a block. Unlike Python, indentation doesn't matter to C, but indenting the inside of every block makes code readable, so always do it.

Printing without \n

C
#include <stdio.h>

int main() {
    printf("Same ");
    printf("line\n");
    printf("New line\n");
    return 0;
}

Comments

C
#include <stdio.h>

int main() {
    // A single-line comment
    /* A comment that can
       span several lines */
    printf("Comments are ignored\n");
    return 0;
}

A missing semicolon

C
#include <stdio.h>

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

The error points at the line after the missing semicolon, because that's where the compiler realises something is wrong. Look one line up.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.