Explanation
The structure of a C program typically consists of various components, including comments, preprocessor directives, function declarations, and the main function. Let me illustrate this with a simple example program:
#include <stdio.h> // Preprocessor directive
// Function declaration
int add(int a, int b);
int main() {
// Variables
int num1, num2, sum;
// Input
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
// Function call
sum = add(num1, num2);
// Output
printf("Sum: %d\n", sum);
return 0; // Return statement
}
// Function definition
int add(int a, int b) {
return a + b;
}
-
Comments:
-
Comments provide human-readable explanations within the code.
-
In the example, ‘//’ is used for single-line comments, and ‘/* */’ is used for multi-line comments.
-
-
Preprocessor Directives:
-
These are instructions to the preprocessor that modify the source code before actual compilation.
-
#include <stdio.h> is a common directive to include the standard input/output library.
-
-
Function Declaration:
-
Function declarations specify the function's name, return type, and parameter types.
-
In the example, ‘int add(int a, int b); ‘declares the’add’ function.
-
-
main() Function:
-
The main() function is the entry point of the program.
-
It contains the program's logic.
-
It returns an integer value (usually 0) to indicate the program's status.
-
-
Variables:
-
Variables are used to store and manipulate data.
-
In the example, ‘num1’, ‘num2’, and ‘sum’ are declared as integer variables.
-
-
Input and Output:
-
‘ Printf ’ is used to display output to the console.
-
‘ Scanf ’ is used to read input from the user.
-
-
Function Definition:
-
The ‘add’ function is defined after the ‘main’ function. It takes two integer parameters and returns their sum.
-
-
Return Statement:
-
The ‘return 0; statement in the ‘main’ function indicates that the program executed successfully.
-
This structure provides a basic framework for C programs. The program starts with the ‘main()’ function, which is where execution begins. Functions are used to modularize code and improve readability and reusability.