Introduction
The best way to learn C programming is by writing and running your first program. Traditionally, the first program prints "Hello, World!".
This simple exercise teaches you the core fundamentals:
- Program structure
- The
main()function - Output statements
- Compilation process
- Running a program
First C Program
#include <stdio.h> // Includes standard I/O library (for printf)
int main() // Main function: program execution begins here
{ // Opening brace: starts the function body
printf("Hello, World!"); // Prints "Hello, World!" to the screen
return 0; // Returns 0 to indicate successful completion
} // Closing brace: ends the function body
Understanding Each Line
Line 1: #include <stdio.h>
This includes the Standard Input Output library. It gives access to essential functions like:
printf()- to display textscanf()- to get user input
Line 2: int main()
This is the main function. Every C program starts execution from main(). The int means the function returns an integer value to the operating system upon completion.
Line 3 and 6: { }
These curly braces define the block of the function. Everything inside these braces belongs to main().
Line 4: printf("Hello, World!");
The printf() function prints whatever is inside the double quotes to the screen.
Line 5: return 0;
This tells the operating system that the program ended successfully.
How to Compile and Run
- 1. Compile: Use the GCC compiler to build your executable:
gcc hello.c -o hello - 2. Run: Execute the compiled program based on your operating system:
- Linux/macOS:
./hello - Windows:
hello.exe
- Linux/macOS:
Console Output
Hello, World!
Flow of Execution
Embedded Focus
In the desktop world, your first C program prints "Hello, World!" to a console. In the embedded world, most microcontrollers do not have a computer screen! For an embedded engineer, the traditional "Hello, World!" is Blinking an LED by toggling a General Purpose Input/Output (GPIO) pin. To print messages for debugging, the printf() function is redirected (or "retargeted") to send characters over a serial interface like UART to your computer's terminal emulator.
Interview Question
Q
Why is main() important in C?
Why is main() important in C?
Because program execution starts from main(). Without it, the compiler wouldn't know where the program begins.