Back to course

Your First C Program: 'Hello World'

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 3: Your First C Program: 'Hello World'

Let's write the iconic first program that prints text to the screen.

The Code (hello.c)

c #include <stdio.h>

int main() { // Print the message to the console printf("Hello, World!\n"); return 0; }

Line-by-Line Explanation

  1. #include <stdio.h>: This line is a preprocessor directive. It tells the compiler to include the contents of the Standard Input/Output header file (stdio.h), which contains the definition for the printf function.
  2. int main(): This is the main function. Every C program execution starts here. int indicates that the function returns an integer value.
  3. { ... }: The curly braces define the body of the function, containing the instructions to be executed.
  4. printf("Hello, World!\n");: The core instruction. printf is used to output text. \n is an escape sequence representing a newline character.
  5. return 0;: This ends the main function and signals the operating system that the program executed successfully (0 usually means success).

Compilation and Execution

  1. Save: Save the code as hello.c.

  2. Compile: Open the terminal in the directory where you saved the file and run: bash gcc hello.c -o hello_program

    • gcc: The compiler command.
    • hello.c: The source file.
    • -o hello_program: Output the executable file named hello_program (or hello_program.exe on Windows).
  3. Execute: Run the generated file: bash ./hello_program

Output:

Hello, World!