Structure of a C Program

Subject: PPS (Programming for Problem Solving)

Contributed By: Sanjay

Created At: February 3, 2025

Question:


Write the structure of a C program. Explain briefly about each section in the structure.

Explanation Video:

Custom Image

Explanation:

Structure of a C Program:

A C program typically follows a specific structure. Here's a breakdown of its main parts:

1. Preprocessor Directives

  • These are commands that are processed before the actual compilation starts. They are used to include libraries or define constants.

  • Example: #include <stdio.h> tells the compiler to include the standard input-output library.

2. Global Declarations

  • This section includes any variables or functions that will be used across the entire program. Global variables can be accessed by all functions.

  • Example: int x = 10; is a global variable.

3. Main Function

  • Every C program must have a main() function, which is the entry point of the program. When the program is executed, the code inside main() is run first.

  • Example

int main() {

   // Code to be executed

   return 0;

}

4. Local Declarations

  • Inside the main() function or other functions, you can declare local variables. These variables can only be used within the function where they are declared.

  • Example: int a = 5; inside main() is a local variable.

5. Executable Statements

  • These are the actual instructions or commands that perform tasks, like calculations, printing output, etc.

  • Example: printf("Hello, World!"); is an executable statement that prints text to the screen.

6. Functions

  • A C program can have multiple functions. Functions allow you to break the program into smaller, manageable parts. They can be declared before or after main() and should be called in main() or other functions.

  • Example

int add(int a, int b) {

   return a + b;

}

 

Example C Program Structure is Given Below:

Source Code:
#include <stdio.h>   // Preprocessor directive

// Global declarations (if needed)
int global_var = 5;

// Function declarations (if needed)
int add(int, int);

int main() {  // Main function
    int a = 10, b = 20;  // Local variable declarations
    printf("Sum is: %d", add(a, b));  // Calling the add function
    return 0;  // Return statement
}

// Function definitions
int add(int x, int y) {
    return x + y;  // Executable statement
}
Share this Article & Support Us:
Status
printf('Loading...');