Skip to content

The Basic of C Programming

Workflow

Workflow A typical workflow in a compiled language is the edit, compile, execute, loop. To start, we first either create or edit the file containing our C program (e.g., first.c) with our favourite editor. This will be our source code.

We then compile our source code using a compiler (e.g., GCC or Clang) to produce an executable code. Typically, when run on a UNIX machine, the file is called a.out. If the program compiles, then we proceed with the next step. Otherwise, we go back to editing our source code.

The next step is to execute the program and test. If we find incorrect result in our testing, we restart from the first step again. This step is performed until we are satisfied with our program or until we have to submit our program. The diagram below summarises the steps.

Workflow

Steps

  1. Create a new C program file (with the extension .c) or edit an existing one.

    • We would recommend the use of vim (or vi improved) as it is available in all UNIX system like sunfire.
  2. Save the file (e.g., first.c).

  1. Compile your C program file from "Edit" step using GCC (e.g., gcc first.c).
  2. You will either:
    1. Produce an executable code (e.g., a.out) then you continue to "Execute" step.
    2. Fail to compile (i.e., compile error) then you repeat "Edit" step to repair the program and remove the compile error.
  1. Execute your executable (e.g., a.out or ./a.out).
  2. You will either:
    1. Get the correct program output and you are satisfied with your work and finish.
    2. Get the incorrect program output then you repeat "Edit" and "Compile" step to repair the program until you get the correct program output.

Hello World

As is the tradition, your first program will be the "Hello World!" program. Copy and paste the following code into a file called HelloWorld.c.

Hello World

HelloWorld.c
1
2
3
4
5
#include <stdio.h>
int main(void) {
  printf("Hello World!\n");
  return 0;
}

HelloWorld.js
1
console.log("Hello World!");
HelloWorld.py
1
print("Hello World!");

You can compile it on a UNIX machine using the command gcc HelloWorld.c. This should produce a file called a.out. You can execute this file using the command ./a.out. There should be Hello World! printed on your screen.

Alternatively, you can test it on the "ReplIt" tab above:

  1. Click on "Shell" tab.
  2. Compile with GCC using gcc main.c (this is the default file name on the website).
  3. See the content of the current folder using ls.
    • You should see three files: a.out, main and main.c.
  4. Execute the code using ./a.out.

If all goes well, your session should look like the following

Manual Compilation
1
2
3
4
5
$ gcc main.c
$ ls
a.out  main  main.c
$ ./a.out
Hello World!

Now, if you want to use a different name for the executable file, you can use the flag -o (this is lowercase "o" for "omega" and not the number zero) followed by the name during compilation. You can test the following.

Manual Compilation with Renaming
1
2
3
4
5
$ gcc main.c -o my_first_c
$ ls
main  main.c my_first_c
$ ./my_first_c
Hello World!

General Form

A simple C program is generally structured as follows:

C Program General Structure

1
2
3
4
5
6
7
#preprocessor directives

main function header
{
  declaration of variables
  executable statements
}

Furthermore, the executable statements usually consists of 3 parts:

  1. Input data
  2. Computation
  3. Output results

Since our hello world program lacks variables, input data and computation, we will use the following program to compute miles to kilometres called MileToKm.c as our example. You can also click on the tabs below to see the highlighted structures.

Mile to Kilometers Conversion

MileToKm.c
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// Converts distance in miles to kilometres.
#include <stdio.h>         /* printf & scanf definitions */
#define KMS_PER_MILE 1.609 /* conversion constant        */

int main(void) {
  float miles,  // input : distance in miles
        kms;    // output: distance in kilometres

  /* Get the distance in miles */
  printf("Enter distance in miles: ");
  scanf("%f", &miles);

  // Convert the distance to kilometres
  kms = KMS_PER_MILE * miles;

  // Display the distance in kilometres
  printf("That equals %9.2f km.\n", kms);

  return 0;
}

MileToKm.c
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// Converts distance in miles to kilometres.
#include <stdio.h>         /* printf & scanf definitions */
#define KMS_PER_MILE 1.609 /* conversion constant        */

int main(void) {
  float miles,  // input : distance in miles
        kms;    // output: distance in kilometres

  /* Get the distance in miles */
  printf("Enter distance in miles: ");
  scanf("%f", &miles);

  // Convert the distance to kilometres
  kms = KMS_PER_MILE * miles;

  // Display the distance in kilometres
  printf("That equals %9.2f km.\n", kms);

  return 0;
}
MileToKm.c
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// Converts distance in miles to kilometres.
#include <stdio.h>         /* printf & scanf definitions */
#define KMS_PER_MILE 1.609 /* conversion constant        */

int main(void) {
  float miles,  // input : distance in miles
        kms;    // output: distance in kilometres

  /* Get the distance in miles */
  printf("Enter distance in miles: ");
  scanf("%f", &miles);

  // Convert the distance to kilometres
  kms = KMS_PER_MILE * miles;

  // Display the distance in kilometres
  printf("That equals %9.2f km.\n", kms);

  return 0;
}
MileToKm.c
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// Converts distance in miles to kilometres.
#include <stdio.h>         /* printf & scanf definitions */
#define KMS_PER_MILE 1.609 /* conversion constant        */

int main(void) {
  float miles,  // input : distance in miles
        kms;    // output: distance in kilometres

  /* Get the distance in miles */
  printf("Enter distance in miles: ");
  scanf("%f", &miles);

  // Convert the distance to kilometres
  kms = KMS_PER_MILE * miles;

  // Display the distance in kilometres
  printf("That equals %9.2f km.\n", kms);

  return 0;
}
MileToKm.c
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// Converts distance in miles to kilometres.
#include <stdio.h>         /* printf & scanf definitions */
#define KMS_PER_MILE 1.609 /* conversion constant        */

int main(void) {
  float miles,  // input : distance in miles
        kms;    // output: distance in kilometres

  /* Get the distance in miles */
  printf("Enter distance in miles: ");
  scanf("%f", &miles);

  // Convert the distance to kilometres
  kms = KMS_PER_MILE * miles;

  // Display the distance in kilometres
  printf("That equals %9.2f km.\n", kms);

  return 0;
}
MileToKm.c
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// Converts distance in miles to kilometres.
#include <stdio.h>         /* printf & scanf definitions */
#define KMS_PER_MILE 1.609 /* conversion constant        */

int main(void) {
  float miles,  // input : distance in miles
        kms;    // output: distance in kilometres

  /* Get the distance in miles */
  printf("Enter distance in miles: ");
  scanf("%f", &miles);

  // Convert the distance to kilometres
  kms = KMS_PER_MILE * miles;

  // Display the distance in kilometres
  printf("That equals %9.2f km.\n", kms);

  return 0;
}
MileToKm.c
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// Converts distance in miles to kilometres.
#include <stdio.h>         /* printf & scanf definitions */
#define KMS_PER_MILE 1.609 /* conversion constant        */

int main(void) {
  float miles,  // input : distance in miles
        kms;    // output: distance in kilometres

  /* Get the distance in miles */
  printf("Enter distance in miles: ");
  scanf("%f", &miles);

  // Convert the distance to kilometres
  kms = KMS_PER_MILE * miles;

  // Display the distance in kilometres
  printf("That equals %9.2f km.\n", kms);

  return 0;
}
MileToKm.py
1
2
3
4
5
6
KMS_PER_MILE = 1.609

miles = float(input("Enter distance in miles: "))
kms = KMS_PER_MILE * miles

print(f"That equals {round(kms,2)} km.")

A Quick Note

  • Starts with #.
  • #include allows us to use codes defined in another file.
  • #define allows us to define a constant.
  • Declaration: <data type> <variable name>;.
  • May be initialised <data type> <variable name> = <value>;.
  • Best practice:
    • Always declare at the beginning of a function.
    • Always initialise before use.
  • One line: // this is comment until end of line.
  • Multi line: /* this is comment until closing */.
    • In ANSI C, only this comment is allowed.
    • But we also allow one line comment.
  • Semi-colon (_i.e., ;) terminates a statement.
    • Unlike JavaScript, semi-colon is not optional.
  • Curly brackets (i.e., {}) indicates a block.
    • Unlike Python, indentation does not matter.

Memory

Memory Snapshot

Memory 01

When we declare a variable, the value of the variable is whatever happen to be in that memory location. This is in contrast to many other programming language where there is a default value, usually 0. In fact, this is one of the reason why a program written in C can execute very fast, because we do not even initialise a variable when we declare it.

Unfortunately, this is also a very common mistake. Many programmers not familiar with C assumes that a variable is automatically initialised to a default value. The state of the memory at the beginning can be represented as follows. Note that the value of the variable miles and kms are unknown and represented as ?.

Memory 02

After the user enters the value of 10.5 into the program, the value is assigned to the variable miles by the line scanf("%f", &miles); The exact mechanism for this will be explained in more details later. It suffices for now to note that after this line executed, the memory looks as follows.

The yellow box shows the changes from the previous state. Previously, the value was unknown as marked by ?. After reading user input, the value is known and it is 10.5.

Memory 03

After the conversion from miles to kilometres, we assign the value to the variable kms. This is done by the line kms = KMS_PER_MILE * miles;. The result is that the memory looks as follows.

Uninitialised Variables

The common mistakes for beginner C programmer is to assume that uninitialised variables contain zero. This is not true as the value is whatever value happen to be in the memory location. For all practical purposes, we can model the value as random.