Structure of a C Program
A C program follows a specific structure that helps the compiler understand what to do. It usually includes headers, the main function, and logic written using statements. Understanding this structure helps in organizing and writing clean code. Here's a typical format:
General Structure:
// 1. Preprocessor Directives
#include <stdio.h>
// 2. Global Declarations (optional)
// 3. main() Function
int main() {
// 4. Variable Declarations
// 5. Code / Logic
return 0;
}
Structure Explanation:
- Preprocessor Directives: Includes header files using
#include
. - Global Declarations: Variables or functions declared outside
main()
and accessible throughout the program. - main() Function: The starting point of execution.
- Variable Declarations: Declares variables before use.
- Statements: Logic like
printf()
, loops, conditions, etc. - Return Statement: Ends the program and returns value to OS.
Note: Saving a C Program File
- Every C program must be saved with the
.c
extension. - This tells the compiler that it's a C source code file.
- For example:
hello.c
program1.c
abc.c
- Make sure the file is saved in the correct directory (like the bin folder of your C compiler) or note the path when compiling.
Sample Program:
#include <stdio.h> // for printf()
#include <conio.h> // for clrscr(), getch()
int main() {
clrscr(); // clears the output screen
printf("Welcome to C!"); // displays message
getch(); // waits for a key press
return 0; // ends program successfully
}
Program Output:
Welcome to C!
(And the program waits for key press because of getch()
)
Explanation of Key Components:
-
#include <stdio.h>: Required for input/output functions like
printf()
. -
#include <conio.h>: (Console Input/Output) — Not part of standard C, used
mainly in Turbo C.
It provides:- clrscr(): Clears the output screen before displaying new output.
- getch(): Waits for a key press so the output window doesn't close immediately.
-
int main(): This is the entry point of the program. It's standard to use
int
so we can return a value to the operating system. - return 0: Tells the OS that the program ran successfully. If you return any non-zero value, it usually indicates an error.
-
void main(): Sometimes used, but
int main()
is preferred according to international C standards (like ANSI/ISO).
Summary:
- A C program must include
main()
function — it's where execution begins. int main()
andreturn 0
are standard for proper completion.clrscr()
andgetch()
are helpful for clean output, especially in Turbo C.conio.h
is not available in all compilers — mainly for DOS-based environments.