Chapter 2: Your First C Program

1. Your First C Program – “Hello, World!”

This is the classic first program every C programmer writes. It simply prints “Hello, World!” on the screen.

C

Output when you run it:

text

2. Structure of a C Program (The Basic Layout)

Every C program follows this fixed structure:

C

Key Points to Remember:

  • Preprocessor lines (#include, #define) come first
  • Exactly one int main() function is required
  • Every statement ends with a ; (semicolon)
  • Code inside { } (curly braces)

3. Compilation and Execution Process

(How your code becomes a running program)

C is a compiled language – so your code goes through these steps:

  1. Write the source code You create a file like hello.c
  2. Preprocessing Compiler replaces #include files, removes comments, handles #define (This is automatic – you don’t see it)
  3. Compilation Converts C code → Assembly code Command: gcc -S hello.c → creates hello.s
  4. Assembly Converts assembly → Machine code (binary) Creates object file: hello.o
  5. Linking Combines your object file + standard libraries (like printf from stdio.h) Creates final executable file
  6. Execution Run the executable → see output on screen

Most common single command (does everything):

Bash
  • gcc = compiler
  • hello.c = your source file
  • -o hello = name of final executable file

Run the program:

  • On Linux / macOS:
    text
  • On Windows:
    text

If you forget -o:

Bash

It creates default executable: a.exe (Windows) or a.out (Linux/macOS)

4. Comments in C

Comments are notes you write for yourself or others – the computer completely ignores them.

Two Types:

Type 1: Single-Line Comment

C

Type 2: Multi-Line Comment

C

Best Practice Example – Full Program with Good Comments

C

Practice Tasks for Today

  1. Copy the Hello, World! program above and run it.
  2. Add your own message and some comments.
  3. Try removing a ; (semicolon) on purpose – compile and see the error.
  4. Write a small program that prints your name and favorite hobby – add comments to every important line.

You may also like...