Back to main

Lab 1 for C programming

Tips for programming are on How to Think about Programming.

Exercises:
Material like this:
foo = bar(baz);
is a code example which can be copy-and-pasted directly into a .c file. Some of these examples will be an entire standalone file; other examples will be an exerpt which must be placed in the appropriate context.

Exercise 1: "Hello, world!" and friends

Background

By convention, the first thing to learn in a new programming language is to print the text "Hello, world!". Although text isn't very exciting by itself, the ability to output text is vital for debugging (fixing programs).

Most programming languages, including C, indicate text with "double quotation marks": the first " indicates the beginning of text. The computer then treates everything until the next " as text.

This causes problems if you want to print an actual " symbol in the output. For that reason, we use escape sequences to represent symbols which are difficult (or impossible) to indicate with plain text.

In addition to telling a compiler how to create an executable file, source code should also tell future programmers why the code does what it does. If anything in the code is unclear, a programmer should add comments which explain the situation. More information about comments is on the good programming style page.

Technical details

Printing text (complete example):

#include <stdio.h>

int main() {
    printf("Hello, world!");

    // wait for a keypress
    getchar();
}

Selected escape sequences (more escape sequences):

SequenceName
\nNew line
\tHorizontal tab
\\Back slash
\'Single quotation mark
\"Double quotation mark

There are two ways of adding comments (code exerpt):

// this is a single-line comment
/* this type of comment can span multiple
   lines; everything is a comment until
   the
   computer sees the ending */

Your task...

Write a short self-introduction (not necessarily truthful!), and a list of items you would buy if given 1, 10, 100, or 1000 pounds. Example output:

Greetings!  I am \Sir Percival\ of the Round Table, hailing from
Vancouver, Canada.  My fair city lies approximately 4,500 miles to
the West.  In my country, we say `eh?' a lot.

Free money, you say?  Well, let's see...
        Pounds   Purchase
        1        A packet of tea biscuits.
        10       Second-hand DVDs of "Still Game", so I can learn Glasgow patter.
        100      An external hard drive for my laptop.
        1000     A visit to my family next Christmas.

Your program should:


(optional: make it funny. We'll like you more. You won't get any marks for being funny, but hey, you'll make a friend! Looking at first-year programming exercises gets really boring.)

... show your work to a demonstrator


Exercise 2: Variables and (simple) Math

Background

Computers would be boring if they didn't do any computation, and variables make computation a lot easier.

Variables must be declared before you can use them. This tells the computer to reserve a piece of memory to store the variable's value.

The computer doesn't care what you call the variable (within reason -- see identifier for the exact requirements), but having descriptive variable names will make your programs much easier to work on.

For the next few weeks, we will use two types of numeric variables: int (an integer), and float (a floating-point, i.e. decimal, number).

There is another type of variable, which is very rarely used by itself: char. This represents one ASCII character; each value (between 0 and 127) represents an entry in the ASCII table.


Text variables are called strings, short for "a string of characters". Technically, they are stored as an array of characters, but we will return to this in the second lab lab. For now, we will not do any modifications of strings.

For reasons which we will discuss in a later lab, you can get an array of a particular variable type by adding [x] to the variable name, where x is the number of variables. For other reasons which we will discuss later, a string's length must be 1 more than the number of characters you want it to hold.

To get a string of 99 characters (recommended), write:
char string_variable[100];

Technical details

Declaring and printing variables, and basic math:
#include <stdio.h>

int main() {
    int x;
    printf("x is currently %i", x);
    printf(", which is completely random!\n");
    printf("  (we probably don't want this)\n\n");
    x = 3;

    float y = 4.1;
    printf("y is currently %f.\n", y);
    printf("Make that shorter: %.2f.\n", y);
    printf("Make that longer: %.8f.\n\n", y);

    int z;
    z = x/y;
    z = x + z * y - y;
    printf("Why does z = %i?\n\n", z);

    printf("We can print multiple ");
    printf("variables: %i %f %i\n\n", x, y, z);

    char a = 71;
    printf("What about this one: %c\n", a);

    // wait for a keypress
    getchar();
}
Examine the above program carefully -- there is a lot of good information in it! Try changing the values of variables, and examine the new output.
We can also declare and print strings.
#include <stdio.h>

int main() {
    char name[100] = "Graham";
    printf("Hi there!  %s greets you!", name);

    // wait for a keypress
    getchar();
}
For now we will only declare and print strings; we won't modify them until the second lab.

Your task...

Save your introduction/story program from Exercise 1 with a new file name: we will be modifying it, but you don't want to lose all your hard work.

Modify the new version of your introduction/story so that your program:

(hint: converting units is an easy way to get some math in there. Change between miles + km, pounds + euros, pounds + kg, human years + cat years, etc. You may need to rewrite part of your self-introduction to introduce some units.)

Think about your variable names. Don't write something like:
distance = distance * 1.609344
Instead, give them more descriptive names, like
distance_km = distance_miles * 1.609344
(Read more about good style)

(optional: invent a new measurement (like "centi-flipsies") and some fancy symbols from the table of operators to convert into them.)

... show your work to a demonstrator


Exercise 3: Keyboard input

Background

Reading numbers from the keyboard is fairly straightforward: declare the variable (reserve space in memory), then read data into that variable (the space in memory).

The & symbol means "the location of memory pointed to by the following variable". Memory management in C is not straightforward, so we postpone this discussing until a later lab. For now, just remember that you need this symbol in front of a numeric variable in your scanf statement.


Reading text is not quite as simple as numbers. As discussed in Exercise 2, we must tell the computer the maximum number of characters. This maximum value must be passed to the scanf function with "%99s".

Specifying the maximum size of keyboard input is critically important. Failure to specify the maximum size will allow the keyboard user to overwrite random pieces of memory. This can lead to random crashes and security flaws. Approximately 50% of all computer security holes come from this problem, which is ridiculously easy to fix.

Technical details

Reading ints and floats:

#include <stdio.h>

int main() {
    int a;
    printf("Enter an integer: ");
    scanf("%i", &a);
    printf("a = %i\n", a);

    float b;
    printf("Enter a float: ");
    scanf("%f", &b);
    printf("b = %f\n", b);

    // wait for a keypress
    getchar();
    // we need two of them because of scanf!
    getchar();
}

Reading strings from the keyboard is more complicated. For reasons that we will discuss in a later lab, we MUST specify a maximum size to the %s scanf command. This is done with %99s (if the variable's size is 100 -- remember that the size must be 1 more than the number of characters we want to hold!).

#include <stdio.h>

int main() {
    // the sizes must match!
    char text[100];
    // no & for this variable
    scanf("%99s", text);

    printf("%s\n", text);

    // wait for a keypress
    getchar();
    // we need two of them because of scanf!
    getchar();
}
Unlike the int and float, we must not use a & in front of a char[] variable in a scanf.

Your task...

Mad libs (similar to "ad-lib") is a popular party game in North America. Somebody writes a story, but removes a few nouns, adjectives, and verbs. Other people must supply words to replace them (often with a clue, such as "an animal name" or "a movement verb"), without knowing the context in which they would be used. The result is nonsensical and sometimes funny. For example:

One day, a ________________ went to _______ and _____________ a ______.
            name of animal           place       verb (past)     noun

(other people supply: "polar bear", "Russia", "ate", and "house".)

Write a program which implements a mad-lib game:


(optional: make it funny)

... show your work to a demonstrator


Exercise 4: Functions

Background

You are familiar with functions in mathematics -- you've handled functions like g(x) = x^2 + 2x - 3. In this case, the function returns a value. The returned value is computed based on the input. You have also seen functions with multiple inputs: h(x,y) = 5x - 6x + x*y.

We use functions like this in programming. In C, we need to specify the type of variable being returned -- int or float. We also need to specify the type of input variables.

We also sometimes use functions which do not return any values -- these are useful if we want to repeat a few commands, or simply for program organization. These functions are called void functions.

Functions must be declared before ("higher in the .c file") they are used.

Note that each function has its own scope of variables. A function cannot refer to a variable which was declared in the int main() function. In fact, you can re-use the same variable name in different functions!

This is the time we have seen variable scope, but we can illustrate the problem even without functions. Consider the following example -- it will not compile. The int x is defined inside an extra code block { ... }. The scope of variable x only lasts for that code block; referring to this variable outside of that scope will produce a compiler error.

int main() {
    {
        int x = 0;
    }
    x = 1;
}
This is one reason why indentation is useful in source code.

Technical details

Simple function:

#include <stdio.h>

float g(float x) {
    return x*x + 2*x - 3;
}

int main() {
    float a = 3.2;
    float b = g(a);
    printf("g(%f) = %f\n", a, b);

    printf("g(5) = %f\n", g(5));

    // wait for a keypress
    getchar();
}
Note the different variables names in the above example!

Various functions:

#include <stdio.h>

int catYears(int human_years) {
    float y = human_years / 7.0;
    // this would be a good place for a comment
    // why did I write the next line?
    int rounded = y+0.5;
    return rounded;
}

float sumOfSquares(float a, float b) {
    return a*a + b*b;
}

void p(int years, float c, char animal[100]) {
    printf("If I were a %s, I'd be ", animal);
    printf("%i years old.\n\n", years);
    printf("The sum of squares ");
    printf("was %f units.\n", c);
}

int main() {
    int my_age = 18;
    float x = 3.3;
    char animal[100] = "cat";

    float years_a = catYears(my_age);
    float sum = sumOfSquares(x,7.4);

    p(years_a, sum, animal);

    // wait for a keypress
    getchar();
}

Your task...

As electrical engineering students, you are familiar with Ohm's Law (V = IR) and calculating the value of resistors in series (R = R1+R2) and parallel (1/R = 1/R1 + 1/R2). Consider the following circuit:

Write a program to calculate the overall current in this circuit.


(optional: you can call functions as inputs to other functions, i.e.

z = f( g(x,y), h(x,y) );
Using this, calculate the current from voltage and Rx values in a single line.)

... show your work to a demonstrator

Move on to Lab 2


Creative Commons LicenseUnless otherwise noted, all materials on these pages are licenced under a Creative Commons Licence.