Blog



C language tutorial: Program Structure
Jacobus Erasmus, 29 July 2018

Let us look at the basic structure of a C program. First, we must install a C compiler. If you are using Windows or Mac, then consider using Ubuntu (or another Linux/BSD OS), which we will be using. Use your operating system's package manager to install build-essential. On Ubuntu, we run the following command in the terminal:

  sudo apt install build-essential  

Now, create a file named 'main.c'. It is convention that C code files end in '.c'. Let main.c contain the following text, which is a basic code skeleton for a C program:

#include <stdio.h>
#include <stdlib.h>
int main()
{
  // comments look like this.
  return 0;
}

The first line tells the compiler to include all the code in the standard input output header file named stdio.h. Likewise, the second line includes the code from the standard library header. These two inclusions allow us to use some basic functions in our program.

The next line begins the main() function. Every C program needs a main() function, as this is the first function that is run in the program. The 'int' in front of 'main()' says that main() will return an integer. The main() function must return an integer, either zero if all went well or some other integer if an error occurred.

Comments in C begin with '//'. Finally, the return 0; line of code simply returns the integer zero. We may omit this line and, if we do, then main() will return zero by default. Hence, our main.c file could look like this, which would do the same thing as the above code:

#include <stdio.h>
#include <stdlib.h>
int main()
{
}

OK, let us modify our main.c code to output the string 'Hello, world.'. To output a string, we use the printf("string to output") function. Our code now looks like this:

#include <stdio.h>
#include <stdlib.h>
int main()
{
  printf("Hello, world.\n");
}

Notice that lines of code in a function must end with ';'. Now that we have written our program, we must compile it into an executable file. We will use the gcc application, which is the GNU project C and C++ compiler. In the terminal, run the following:

gcc main.c -o main

The above command tells gcc to compile the 'main.c' code file into an executable file named 'main'. We now have a main executable file. To run it:

./main

You should see the output 'Hello, world.'. Congratulations, you now know how to write a basic C program.


Exercises

1. In the line of code printf("Hello, world.\n"); the '\n' in the string represents a line break. Remove '\n' from the string, recompile the code, and run the program to see what happens.

2. Memorise the code skeleton, the printf function, and the gcc command. Delete the main.c and main files and recreate them from memory. That is to say, without looking at your notes or searching for help, write a C program that outputs the string 'Hello, world.'.