Dr. Roger Ianjamasimanana

The basic structure of the C programming language

By Dr. Roger Ianjamasimanana

Understanding the structure of a C program is fundamental for beginners in the C programming lanuguage. A well-structured program not only enhances readability but also ensures maintainability and scalability. This lesson explains the essential components that constitute a C program. I will guide you through each element with clear explanations and practical examples.

1. Basic structures of a C program

A C program comprises various elements that work together to perform specific tasks. These elements include preprocessor directives, functions, variables, statements, and comments. Understanding how these components interact within a program's framework is crucial for writing efficient and error-free code.

2. Preprocessor directives

Include statements

Preprocessor directives are instructions that are processed before the actual compilation of the code begins. The most common preprocessor directive is the #include statement, which incorporates the contents of another file into the current file. This is typically used to include standard library headers or user-defined headers. For example, when you write #include in your code, the program locates the stdio.h file in the system’s standard library directories. The contents of stdio.h are literally copied and pasted into your source file at the location of the #include directive. In other words, The #include line in your code is replaced by the actual content of stdio.h. This means that all the function declarations, macros, and type definitions in stdio.h become part of your code.

Standard headers

Standard headers provide access to standard library functions. For example, #include <stdio.h> includes the Standard Input Output library, which allows you to use of functions like printf() and scanf().

#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}
        
In the above code, if we forgot to write #include <stdio.h>, the program would complain since we used the printf statement, which is part of the stdio.h library.

User-defined headers

User-defined headers are created by programmers to organize their code into reusable modules. They are included using double quotes. For instance, you can write your own myheader.h library and include it in your code as #include "myheader.h".

3. The main function

What is the main function in C?: The main() function is the entry point of every C program. When the program is executed, the execution starts from the main function. It typically returns an integer value to the operating system upon completion.

Basic syntax of the main function

The basic syntax of the main function is as follows:


int main() {
    // Your code here
    return 0;
}
    

- int: specifies that the function returns an integer. - main: the name of the function. - return 0;: indicates successful termination of the program.

4. Variables

Variables are used to store data that can be manipulated within a program. Each variable in C must be declared with a specific data type, which determines the size and layout of the variable's memory.

4.1 Declaration and Initialization

Declaring a variable informs the compiler about the variable's type and name. Initialization assigns an initial value to the variable at the time of declaration.

#include <stdio.h>

int main() {
    int number;          // Declaration
    number = 10;         // Initialization

    float pi = 3.14;     // Declaration and initialization

    printf("Number: %d\n", number);
    printf("Pi: %.2f\n", pi);
    return 0;
}
    

4.2 Data types

C supports various data types, categorized into primary and derived types.

4.2.1 Primary data types

Primary data types include:

  • int: Integer type for whole numbers.
  • float: Floating-point type for decimal numbers.
  • double: Double-precision floating-point type.
  • char: Character type for single characters.

4.2.2 Derived data types

Derived data types are built from primary data types:

  • Arrays: Collections of elements of the same type.
  • Pointers: Variables that store memory addresses.
  • Structures: User-defined data types that group different types of variables.
  • Unions: Similar to structures but allow storing different data types in the same memory location.

5. Statements

Statements are the instructions that perform actions within a program. They can be simple, like variable assignments, or complex, involving control flow mechanisms.

5.1 Expression statements

These statements evaluate expressions and often involve assigning values to variables or performing arithmetic operations.


int a = 5;          // Assignment statement
a = a + 10;         // Arithmetic operation
    

5.2 Control flow statements

Control flow statements determine the order in which instructions are executed. They include conditional statements and loops.

5.2.1 Conditional statements

Conditional statements execute code blocks based on certain conditions.

#include <stdio.h>

int main() {
    int number = 10;

    if (number > 0) {
        printf("Positive number.\n");
    } else if (number < 0) {
        printf("Negative number.\n");
    } else {
        printf("Zero.\n");
    }

    return 0;
}
        

5.2.2 Loops

Loops allow repetitive execution of code blocks.

5.2.2.1 For Loop

The for loop is used when the number of iterations is known.

#include <stdio.h>

int main() {
    for(int i = 1; i <= 5; i++) {
        printf("Iteration %d\n", i);
    }
    return 0;
}
            
5.2.2.2 While loop

The while loop continues as long as a condition is true.

#include <stdio.h>

int main() {
    int i = 1;
    while(i <= 5) {
        printf("Iteration %d\n", i);
        i++;
    }
    return 0;
}
            
5.2.2.3 Do-while loop

The do-while loop executes the code block at least once before checking the condition.

#include <stdio.h>

int main() {
    int i = 1;
    do {
        printf("Iteration %d\n", i);
        i++;
    } while(i <= 5);
    return 0;
}
            

6. Functions

Functions are reusable blocks of code that perform specific tasks. They help in organizing code, making it modular and easier to manage.

6.1 Defining functions

A function is defined by specifying its return type, name, and parameters.

#include <stdio.h>

// Function declaration
int add(int a, int b);

int main() {
    int sum = add(5, 10);
    printf("Sum: %d\n", sum);
    return 0;
}

// Function definition
int add(int a, int b) {
    return a + b;
}
    

6.2 Calling functions in C

To execute a function in C, you call it by its name and pass the required arguments.


// Example of calling a function
int result = add(3, 7);
printf("Result: %d\n", result);
    

6.3 Return types and parameters

Functions can return values of specified types and accept parameters to process dynamic data.


// Function with no return value (void)
void greet() {
    printf("Hello!\n");
}

// Function with multiple parameters
float average(float a, float b, float c) {
    return (a + b + c) / 3;
}
    

7. Comments

Comments are non-executable lines in the code that provide explanations or annotations. They are crucial for improving code readability and maintainability.

Single-line comments

Single-line comments start with // and extend to the end of the line.


// This is a single-line comment
int a = 5; // Variable declaration
    

Multi-line comments

Multi-line comments are enclosed between /* and */ and can span multiple lines.


/*
This is a multi-line comment.
It can span multiple lines.
*/
int b = 10;
    

8. Example program

Let's put together all the structures we've discussed into a complete C program that calculates the factorial of a number.

#include <stdio.h>

// Function to calculate factorial
int factorial(int n);

int main() {
    int number;
    printf("Enter a positive integer: ");
    scanf("%d", &number);

    // Check for negative input
    if(number < 0) {
        printf("The factorial of a negative number doesn't exist.\n");
    }
    else {
        printf("The factorial of %d is %d.\n", number, factorial(number));
    }

    return 0;
}

// Function definition
int factorial(int n) {
    if(n == 0)
        return 1;
    else
        return n * factorial(n - 1);
}
    

Explanation of the code:

  • Include statement: includes the Standard Input Output library.
  • Function declaration: declares the factorial function.
  • Main function:
    • Prompts the user to enter a positive integer.
    • Uses scanf() to read the input.
    • Checks if the input is negative and handles accordingly.
    • Calls the factorial function to compute the factorial.
  • Factorial function:
    • Uses recursion to calculate the factorial of a number.
    • Returns 1 if n is 0 (base case).
    • Otherwise, returns n * factorial(n - 1).

9. Concluding remarks

To understand the structure of a C program, you need to learn preprocessor directives, the main function, variables, statements, functions, and comments. Try to master them and you will be able to create a well-organized and maintainable programs.

feature-top
Readers’ comment
feature-top
Log in to add a comment
🔐 Access