2077 4

BIT102 ยท 2077 ยท 5 marks

What is the basic structure of a C program? Explain each part.

What is the basic structure of a C program? Explain each part. [5]

C ProgrammingChapter 1: Fundamentals of C ProgrammingBasic structure of C program

Quick answer

A C program is organized into several distinct sections. Below is the general template: Contains comments about the program such as program name, author, date, and purpose; Written using /; Ignored by the compiler; meant for human readability.

Basic Structure of a C Program


Basic Structure of a C Program

A C program is organized into several distinct sections. Below is the general template:

/* Documentation Section */
// Program description, author, date

/* Link Section */
#include <stdio.h>
#include <stdlib.h>

/* Definition Section */
#define PI 3.14159

/* Global Declaration Section */
int globalVar = 10;

/* Main Function */
int main()
{
    /* Local Declaration */
    int a, b;

    /* Executable Statements */
    printf("Hello, World!\n");

    return 0;
}

/* User-Defined Functions */
void myFunction()
{
    // function body
}

Explanation of Each Part

1. Documentation Section

  • Contains comments about the program such as program name, author, date, and purpose.
  • Written using /* ... */ (multi-line) or // (single-line).
  • Ignored by the compiler; meant for human readability.
  • Contains header file inclusions using #include.
  • Tells the compiler to include standard library files before compilation.
  • Example: #include <stdio.h> includes standard input/output functions like printf() and scanf().

3. Definition Section

  • Contains macro definitions using #define.
  • Defines symbolic constants or macros used throughout the program.
  • Example: #define PI 3.14159

4. Global Declaration Section

  • Declares global variables and function prototypes.
  • Global variables are accessible by all functions in the program.
  • Example: int count = 0;

5. Main Function (main())

  • The entry point of every C program; execution always begins here.
  • Contains two parts:
    • Local Declaration: Variables declared inside main().
    • Executable Statements: The actual logic, calculations, input/output operations.
  • Returns an integer value (typically 0 to indicate successful execution).

6. User-Defined Functions

  • Functions written by the programmer to perform specific tasks.
  • Defined after main() (or declared before using prototypes).
  • Promotes modularity and code reusability.

Summary Table

SectionPurpose
DocumentationComments and description
LinkInclude header files
DefinitionDefine constants/macros
Global DeclarationDeclare global variables
main()Program execution starts here
User-Defined FunctionsCustom reusable functions

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.