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
#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 theprintffunction.int main(): This is the main function. Every C program execution starts here.intindicates that the function returns an integer value.{ ... }: The curly braces define the body of the function, containing the instructions to be executed.printf("Hello, World!\n");: The core instruction.printfis used to output text.\nis an escape sequence representing a newline character.return 0;: This ends themainfunction and signals the operating system that the program executed successfully (0 usually means success).
Compilation and Execution
-
Save: Save the code as
hello.c. -
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 namedhello_program(orhello_program.exeon Windows).
-
Execute: Run the generated file: bash ./hello_program
Output:
Hello, World!