Chrysolites Tech Academy

Introduction to Computer Science: Harvard CS50 · Course book

Chapter 2: Writing and Compiling C

Pairs with Lesson 2: Programming in C

Scratch lets you build programs from blocks. Most real software is written as text, in a programming language with precise rules. This chapter introduces C, a language created in the early 1970s that still runs operating systems, databases and countless devices. C is demanding, because it does very little for you, but that is exactly why it is worth learning first: you see what the computer is really doing. The chapter covers how a C program is written and turned into something a computer can run, the building blocks of the language, and two surprising ways in which numbers on a computer can go wrong.

From source code to a running program

The classic first program prints a greeting.

#include <stdio.h>

int main(void)
{
    printf("hello, world\n");
}

Every piece has a purpose. The first line includes a header file, stdio.h, which tells the compiler about standard input and output functions such as printf. The line beginning with main defines the function where every C program starts. Curly braces group the lines that belong together. printf prints text, and the \n at the end is an escape sequence meaning "new line". Each statement ends with a semicolon, and leaving one out is among the most common beginner errors.

The text you write is called source code. A computer's processor cannot run it directly; it understands only machine code, long sequences of binary instructions. A program called a compiler translates one into the other. With a compiler named clang, you would type clang hello.c, which produces a runnable file, and then run it. A helper tool called make, given the command make hello, works out the right compiler command for you.

Source codehello.c, readable textCompilertranslates and checksMachine codebinary the processor runs make hello./hello If the source code breaks the language's rules, the compiler stops and reports an error instead.
Figure 2.1 — Compiling. Source code is translated into machine code once, and the resulting program can then be run as many times as you like.

Programs become useful when they respond to input. A helper library used in teaching provides a function, get_string, that asks the user to type something. Its result can be stored in a variable and then printed using a format code, a placeholder that printf fills in.

string name = get_string("What's your name? ");
printf("hello, %s\n", name);

Here %s means "insert a string here", and the value of name is put in its place.

Types, variables and operators

In C every variable has a type, fixed when the variable is declared, which tells the computer how many bytes to set aside and how to interpret them. Table 2.1 lists the common ones, with typical sizes on modern computers.

TypeHoldsTypical sizeFormat codeExample
intWhole numbers4 bytes%iint age = 21;
longLarger whole numbers8 bytes%lilong views = 3000000000;
floatNumbers with a decimal point4 bytes%ffloat price = 2.50;
doubleDecimal numbers with more precision8 bytes%fdouble pi = 3.14159265;
charA single character1 byte%cchar grade = 'A';
booltrue or false1 byte—bool done = false;
stringText (provided by a teaching library)varies%sstring name = "Ada";

Arithmetic uses the familiar symbols +, −, * and /, plus % for the remainder after division: 17 % 5 is 2. One trap catches almost everyone. Dividing one int by another throws away the fraction: 7 / 2 gives 3, not 3.5, because the result must be an int too. To get 3.5, at least one of the numbers must be a decimal type, for example (float) 7 / 2.

The single equals sign means assignment: counter = counter + 1 sets counter to one more than before. C offers shorter forms, counter += 1 and counter++, that do the same thing. Comparisons use == for "equal to", != for "not equal to", and <, >, <= and >= for order.

Conditions, loops and functions

Conditions work as in Scratch, written with if, else if and else.

if (x < y)
{
    printf("x is less than y\n");
}
else if (x > y)
{
    printf("x is greater than y\n");
}
else
{
    printf("x is equal to y\n");
}

Conditions can be combined with && for "and" and || for "or". A test such as (c == 'y' || c == 'Y') accepts either a lower-case or an upper-case answer.

C has three kinds of loop. A while loop repeats as long as a condition is true. A for loop packs a starting value, a condition and an update into one line, which suits counting:

for (int i = 0; i < 3; i++)
{
    printf("meow\n");
}

This sets i to 0, prints "meow", adds 1 to i, and repeats while i is less than 3, so it prints three times, with i equal to 0, 1 and 2. A do-while loop runs its body at least once before checking the condition, which makes it ideal for asking the user for input until they type something valid, such as a positive number.

Loops can be placed inside other loops. To print a square of hashes three wide and three tall, an outer loop counts the rows and an inner loop prints the hashes in each row:

for (int row = 0; row < 3; row++)
{
    for (int col = 0; col < 3; col++)
    {
        printf("#");
    }
    printf("
");
}

The inner loop runs 3 times for each of the 3 passes of the outer loop, so 3 × 3 = 9 hashes are printed, with a new line after each row. Changing the inner condition to col <= row would print a staircase instead: one hash, then two, then three.

As programs grow, repeated code should become a function with its own name. A function can take inputs, called parameters, and give back an output, called a return value. Writing int square(int n) defines a function that receives an int called n and returns an int. Breaking a program into well-named functions is abstraction again: once square works, the rest of the program can use it without thinking about how.

A related habit is to avoid unexplained "magic numbers". If a program uses 3 as the height of a pyramid in several places, define it once with a name, such as const int HEIGHT = 3;, so the meaning is clear and a change needs making in only one place.

Style matters. A program is read far more often than it is written. Consistent indentation, meaningful names and short comments explaining why, not what, make code easier to understand, to fix and to change.

When the compiler finds a mistake, it prints an error message giving the file, the line number and a description. The first message is the one to read; later ones are often knock-on effects of the first. A missing semicolon, an undeclared variable or a forgotten #include line accounts for a large share of beginners’ errors. When a program compiles but behaves wrongly, the simplest debugging tool is to add temporary printf lines showing the values of variables at each step, so you can see exactly where reality departs from what you expected.

When numbers go wrong

Computers store numbers in a fixed number of bits, and that has consequences.

Integer overflow. An int of 4 bytes, 32 bits, can hold values up to 2,147,483,647. Add 1 to that and there is no room for the answer; the bits wrap around and the value becomes a large negative number. The effect is easiest to see with a tiny counter of 3 bits, which can hold 0 to 7. Counting upwards, 7 is 111 in binary; adding 1 should give 1000, but the fourth bit has nowhere to go, so only 000 remains and the counter reads 0.

overflow: 7 + 1 becomes 0 07 0816number of times 1 has been added value stored in a 3-bit counter
Figure 2.2 — Integer overflow in miniature. A 3-bit counter climbs to 7 and then wraps back to 0, because the answer needs a fourth bit that does not exist.

Overflow has caused real failures. Many computers record time as the number of seconds since the start of 1970, and if that count is held in a signed 32-bit integer it will overflow on 19 January 2038, a problem known as the Year 2038 problem. Using 64-bit integers postpones the limit by billions of years.

Floating-point imprecision. Most decimal fractions cannot be written exactly in binary, just as one third cannot be written exactly in decimal. A float stores the nearest value it can. Ask C to print 0.1 as a float to 20 decimal places, and you get 0.10000000149011611938. A double is far more precise but still not exact. For most purposes the difference is negligible, but it means you should never test two decimal results for exact equality, and that money is often counted in whole cents instead of fractions of a pound or dollar.

Check your understanding

  • What does a compiler do, and why is it needed?
  • What does 7 / 2 give when both numbers are ints, and how would you get 3.5? (Answer: 3; cast one to a float, as in (float) 7 / 2.)
  • What is 23 % 4? (Answer: 3.)
  • How many times does for (int i = 0; i < 5; i++) run its body? (Answer: 5, with i from 0 to 4.)
  • When is a do-while loop a better choice than a while loop?
  • A 4-bit counter holds 15. What does it hold after adding 1? (Answer: 0, because 16 needs a fifth bit.)
  • Why should you not test whether two float results are exactly equal?

Install Chrysolites Tech Academy

Android / Chrome / Edge: open the browser menu and choose Install app or Add to Home screen.

iPhone / iPad (Safari): tap the Share button, then Add to Home Screen.