C First Program
The Main Function
Execution of every C program begins inside the function named main -- the operating system looks specifically for this function and calls it first, regardless of how many other functions your file defines.
Example: The Main Function
#include <stdio.h>
int main() {
printf("Execution starts here, inside main.");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Printing Output
printf writes formatted text to the screen and is how a C program produces any visible output; without it (or a similar output call), your program could run perfectly and you'd never know, since nothing would appear on screen.
Example: Printing Output
#include <stdio.h>
int main() {
printf("Hello, World!");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Returning Zero
Returning 0 from main is a signal to the operating system (and any script or tool that launched your program) that execution completed without errors -- returning a non-zero value is the conventional way to report failure.
Example: Returning Zero
#include <stdio.h>
int main() {
printf("Program completed successfully.");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Header Files
#include <stdio.h> pulls in the declarations for standard input/output functions like printf and scanf from the C standard library; without it, the compiler wouldn't know these functions exist and would refuse to compile your call to them.
Example: Header Files
#include <stdio.h>
int main() {
printf("stdio.h provides printf and scanf declarations.");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Executing the Program
Compiling and actually running your program -- not just getting it to compile cleanly -- is the only way to confirm it behaves the way you expect; a program with zero compiler errors can still produce completely wrong output.
Example: Executing the Program
#include <stdio.h>
int main() {
int result = 5 / 2;
printf("Result: %d", result);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 21 topics to unlock
0/21 topics done
Complete these topics first:
- C Introduction
- C History & Features
- C Environment Setup
- C First Program
- C Syntax & Structure
- C Statements
- C Comments
- C Keywords & Identifiers
- C Data Types
- C Character Data Type
- C Numeric Data Types
- C Decimal (Floating-Point) Numbers
- C sizeof Operator
- C Extended Data Types
- C Type Conversion
- C Booleans
- C Variables
- C Changing Variable Values
- C Multiple Variables
- C Constants
- C Fixed-Width Integers