top

Search

C Tutorial

.

UpGrad

C Tutorial

Structure of C Program

Introduction

Programming in C is like constructing a building. You need to set up the foundation, erect the pillars, and finally, build the floors. In C, the foundation is the header files, the pillars are the functions, and the floors are the statements and expressions. Understanding this structure is vital for writing effective and efficient C programs.

Created in 1972, this procedural language was designed to offer users a system language that is efficient and flexible to both users as well as the system. It has a structure that is easy to understand and follow, which makes it a great language to start with if you're new to programming. 

In the subsequent sections, we will cover the basic structure of a C program, including header files, main functions, and other functions.

Understanding the Structure of the C Program

The structure of a C program consists of the following sections:

  1. Documentation section

  2. Preprocessor directives / Header files

  3. Global variables

  4. Main function

  5. Other functions

Header files in C programs

Header files are the files that contain the definitions of preprocessor commands. These commands tell the compiler to preprocess the source code before compiling. They typically end with the ".h" extension.

Some commonly used header files include- 

  • stdio.h: Contains the definitions of functions for performing input and output operations in C.

  • stdlib.h: Contains the definitions of functions for performing general functions such as dynamic memory allocation, random number generation, and so on.

  • string.h: Contains the definitions of functions for performing operations on strings.

For example, to include the stdio.h header file in your program, you would write:

#include<stdio.h>

Sections of the C Program

As we mentioned earlier, a typical C program consists of the following sections:

  1. Documentation section: The documentation section consists of a set of comment lines giving the name of the program, the author, and other details, which the compiler ignores.

  1. Preprocessor directives / Header files: These are the lines in the program that start with '#'. As we discussed earlier, they are used to include header files in the program.

  1. Global variables: These variables are declared outside all the functions and can be accessed from any program part.

  1. Main function: Every C program must have one main function. The execution of the program starts from the main function.

  1. Other functions: These are the additional functions you write for your program. They must be declared and defined in your program before you use them.

Basic Structure of C Program

The basic structure of C program is as follows:

// Documentation section

// Preprocessor directives / Header files
#include<stdio.h>

// Global variables
int global_var;

// Main function
int main() {
    // statements and expressions
    return 0;
}

// Other functions
void otherFunction() {
    // statements and expressions
}

Overview of the basic structure of a C program

In the basic structure of a C program given above, we first have the documentation section, where we provide comments about the program, its author, and other details. This is followed by the preprocessor directives or the header files section, where we include the header files needed for our program.

Next, we declare the global variables that are accessible throughout the program. After that, we have the main function where the execution of the program starts. Inside the main function, we write our statements and expressions. At the end of the main function, we return an integer value, usually 0, to indicate that the program has ended successfully.

Finally, we define any other functions we may need in our program. These functions can be called from the main function or from any other function in the program.

Explanation of each section of a C program - header files, main function, and other functions

Let's explore each section in more detail:

  1. Header Files: As explained earlier, header files contain the definitions of preprocessor commands. These commands inform the compiler to preprocess the source code before compiling. They are included in the program using the #include directive. For example, #include <stdio.h> includes the stdio.h header file that contains functions like printf() and scanf().

  1. Main Function: The main function is the entry point of every C program. It's where the execution of the program starts. It must return an integer value to indicate whether the program execution was successful or not. A return value of 0 typically means the program has been executed successfully. The main function can take arguments, but it's not mandatory.

Here is a simple main function:

int main() {
    printf("Hello, World!");
    return 0;
}

In this example, we print "Hello, World!" to the console and then return 0 to indicate successful execution.

3. Other Functions: Other functions can be user-defined and help modularise the code, making it more readable and maintainable. Here's an example of one such function that determines the sum of two values:

int sum(int a, int b) {
    return a + b;
}


This function takes two integers as input and returns their sum. You can call this function from the main function like so:

int main() {
    int result = sum(5, 3);
    printf("The sum is: %d", result);
    return 0;
}

Example to understand the structure of a C program

Now, let's write a complete C program to understand its structure better. We will write a program that calculates the area of a circle.

// Documentation section
// Program to calculate the area of a circle

// Header files
#include <stdio.h>

// Global variable
#define PI 3.14159

// Function to calculate the area of a circle
double calculateArea(double radius) {
    return PI * radius * radius;
}

// Main function
int main() {
    double radius, area;

    printf("Enter the radius of the circle: ");
    scanf("%lf", &radius);

    area = calculateArea(radius);

    printf("The area of the circle is: %.2lf\n", area);

    return 0;
}

In this program, we start with the documentation section where we describe the program. Then we include the necessary header files. In this case, we only need stdio.h for input and output functions.

We declare a global constant PI which is accessible throughout the program. Then, we define a function calculateArea() that takes the radius of a circle as input and returns the area.

In the main function, we ask the user for the circle's radius, calculate the area using the calculateArea() function, and print the result.

Apart from the barebones structure that we have discussed so far, let’s navigate through a few more crucial concepts found in the structure of C program! 

Standard Library Functions in C

The C language comes with a rich set of functions, collectively known as the standard library. These functions are declared in various header files, and you can use them by including the appropriate header file in your program.

Standard library functions are grouped into several categories, including:

  • Input/Output functions: These functions are used for input and output operations. They are declared in the stdio.h header file. Examples include printf(), scanf(), getchar(), putchar(), etc.

  • String handling functions: These functions are used for manipulating strings. They are declared in the string.h header file. Examples include strcpy(), strlen(), strcmp(), etc.

  • Math functions: These functions are used for mathematical operations. They are declared in the math.h header file. Examples include pow(), sqrt(), sin(), etc.

  • Character handling functions: These functions are used for handling character data. They are declared in the ctype.h header file. Examples include isdigit(), isalpha(), toupper(), etc.

Here's an example of using a standard library function:

#include <stdio.h>
#include <math.h>

int main() {
    double number = 9.0;
    double square_root = sqrt(number);

    printf("The square root of %.2lf is %.2lf\n", number, square_root);

    return 0;
}

In this program, we use the sqrt() function from the math.h header file to calculate the square root of a number.

Control Structures in C

Control structures control the flow of execution of the program. They are divided into three categories:

  • Sequential Control Structure: This is the default control structure where the statements are executed in the same order in which they appear.

  • Selection Control Structure: This allows a set of statements to be executed based on a condition. The control structures used for selection are if, if-else, and switch.

  • Loop Control Structure: This allows a set of statements to be executed repeatedly based on a condition. The control structures used for looping are for, while, and do-while.

Here's an example of using a control structure in a C program:

#include <stdio.h>

int main() {
    int number;

    printf("Enter an integer: ");
    scanf("%d", &number);

    if (number % 2 == 0) {
        printf("%d is even.\n", number);
    } else {
        printf("%d is odd.\n", number);
    }

    return 0;
}

In this program, we use the if-else control structure to check whether a number is even or odd.

Error Handling in C

While writing a C program, it's essential to handle errors that might occur during the execution of the program. The error handling mechanisms in C are limited, but we can use some methods like function return values and the errno global variable to handle errors.

For instance, when a function fails, it can return a special value indicating the failure. The program can then check this value to determine whether the function has failed and take appropriate action.

Here's an example:

#include <stdio.h>

int divide(int a, int b, int *result) {
    if (b == 0) {
        return -1;  // Return an error code
    }

    *result = a / b;
    return 0;  // Return success code
}

int main() {
    int result;

    if (divide(10, 2, &result) == -1) {
printf("An error has occurred!\n");
} else {
printf("The result is: %d\n", result);
}
return 0;
}

In this program, the ‘divide’ function returns -1 when an error occurs (when trying to divide by zero). In the main function, we check the return value of ‘divide’ to see whether an error has occurred.

Remember that proper error handling is crucial for developing reliable and robust software. It allows your program to react gracefully to unexpected situations and makes it easier to debug and maintain.

Conclusion

In this tutorial, we have learned about the structure of a C program, including the roles of header files, the main function, and other functions. We have also seen how to write a simple C program. Understanding this structure is crucial for writing effective C programs. As you continue learning, you will come across more complex structures, but the basic structure remains the same.

Along with navigating the challenging yet insightful journey of improving your programming skills, enrolling in Full Stack Software Development Bootcamp offered by upGrad can be an exceptional addition to your resume. From in-demand topics taught by industry experts, this program will ensure you emerge as a leading developer in the full-stack industry!

FAQs

  1. Why is the main function necessary in a C program?
    The main function serves as the entry point for program execution. Regardless of its location within the source code, the execution of the program always begins with the main function. It can also return a value to the operating system indicating whether the program execution was successful or not.

  1. What are global variables in a C program?
    Global variables are variables that are declared outside all functions and are accessible throughout the program. These variables retain their value throughout the lifetime of the program.

  1. Why do we return 0 from the main function?
    In C programming, returning 0 from the main function signifies that the program has ended successfully. Any other value (typically 1) indicates some kind of failure.

  1. What is the role of comments in a C program?
    Comments are used to explain the source code and make it more readable. They can be used to include information such as the author, date, purpose of the program, and any relevant details about the code. The compiler ignores comments while compiling the code.

Leave a Reply

Your email address will not be published. Required fields are marked *