Back to main

Lab 2 for C programming

Exercises:

Exercise 5: if conditionals

Background

The logic of an if statement is fairly simple. If the statement is true, the code block (indicated by a statement or the contents of a {...} block) is run. A closely relared command is the if ... else, which acts precisely as you would expect.

Here are two cautions to avoid common problems.
  1. In C, x = 1 and x == 1 do completely different things:
    • The single = is an assignment operator: it changes to the value of x to be 1.
    • The double == is the comparison operator: it returns true if x is equal to 1.
  2. If you forget to use the { ... } code block, then it will be very easy to make a mistake later on. The computer will happily execute statements which you did not think would be running. This is illustrated at the bottom of the "condititonal" example.

Technical details

Conditional:

#include <stdio.h>

int main()
{
    int x = 3;

    if (x == 4) {
        // this line will not be printed
        printf("x is equal to 4.\n");
    }

    // one of these two lines will be printed
    if ((x > 10) && (1 != 0)) {
        printf("Expression is true.\n");
        printf("x is greater than 10.\n");
    } else {
        printf("Expression is false.\n");
        printf("x is not greater than 10.\n");
    }

    // something weird happens here!
    if (x > 10)
        printf("Expression is true.\n");
        printf("x is greater than 10.\n");

    getchar();
}

The logical operators (not !) (and &&) (or ||) are particularly useful with if. Occasionally the exclusive or ^ is useful. Parentheses () are highly encouraged when using logical operators.

Generating a random number:

#include <stdio.h>
#include <stdlib.h>  // extra includes!
#include <time.h>

/* Get a random number from 0 to 0.9999999
   (you don't need to understand this function)
   ***** DON'T MODIFY THIS FUNCTION *****
 */
float getRand() {
    return rand() / (RAND_MAX+1.0);
}

int main() {
    srand( time(NULL) ); // init random
    getRand(); // kick-start the random numbers

    float number = getRand();
    printf("Random number: %f\n", number);
    getchar();
}
getRand() requires extra #include files!

Your task...

Create a "guessing game" program. Your program should:


(optional: instead of guessing an int, ask players to guess a float. Then, instead of trying to guess exactly the right number, the players win if they guess a number within 0.1 of the correct value.)

... show your work to a demonstrator


Exercise 6: While loops

Background

The simplest loops in C are while loops. These loops are very similar to if statments. The difference is that there is not else statement included in a while loop, and the { ... } code block will be repeated as long as the statement is true.

There is no built-in true statement in C, so we use 1 for true and 0 for false.
To stop an infinite loop, use ctrl-c

A closely-related form is the do ... while loop. Examine the code presented -- is there any difference in the output? Try setting int i=10;

Technical details

Infinite loops are fun:

#include <stdio.h>

int main()
{
    while (1) {
        printf("Infinite loop is infinite.\n");
    }
    getchar();
}

Non-infinite loops are more useful:

#include <stdio.h>

int main()
{
    int i = 0;
    while (i < 10) {
        printf("The loop has repeated ");
        printf("%i times.\n", i);
        i++;
    }
    getchar();
}

Another form of loop:

#include <stdio.h>

int main()
{
    int i = 0;
    do {
        printf("The loop has repeated ");
        printf("%i times.\n", i);
        i++;
    } while (i < 10);
    getchar();
}

Your task...

Save your guessing game from Exercise 5 with a new file name; we will be modifying it, but you don't want to lose all your hard work.

Modify your guessing game:


(optional: randomly change the rules -- instead of always going from 1 to 32, let the computer randomly decide to do 100 to 131, -97 to -66, etc. If you change the size of the range, you can't compare high scores for different games. However, you could program the computer to randomly select "all numbers divisible by 4 between 32 and 156" and the like.)

... show your work to a demonstrator


Exercise 7: For loops

Background

A loop that counts up (or down) is the most common type of loop, so most programming languages have a short-cut: the for loop.

This loop squishes the initial setting, conditional "do we continue", and ending "how to change the variable" into a single line. Given a statement of the form:

for (init; run_loop?; after_loop) {
   ...
}

Technical details

The most common form of loop is this:

#include <stdio.h>

int main()
{
    int i;
    for (i=0; i<10; i++) {
        printf("The loop has repeated ");
        printf("%i times.\n", i);
    }
    getchar();
}

Here's a weird loop:

#include <stdio.h>

int main()
{
    int i;
    for (i=2000; i>0; i=i/2-3) {
        printf("What is this loop ");
        printf("doing?  i is %i\n",i);
    }
    getchar();
}

Your task...

Back in the good old days, there were no fancy graphics in computer games; we used text to represent everything. Your task is to draw a room from a family of games called Roguelikes -- the player (represented by the @ symbol) must explore a dungeon.

2x2 room, player at 0,1:
+--+
|..|
|@.|
+--+

5x3 room, player at 1,2:
+-----+
|.....|
|.....|
|.@...|
+-----+

14x8 room, player at 8,5:
+--------------+
|..............|
|..............|
|..............|
|..............|
|..............|
|........@.....|
|..............|
|..............|
+--------------+

Your task is to write a function (with extra "helper" functions) to draw such a room.


(optional: combine this exercise with keyboard input -- let the player move around in the room, bump into walls, etc. Ask the user to turn on the numlock key and to press enter after every move, then you can read his moves by reading ints from the keyboard. Use a while loop for this movement.)

... show your work to a demonstrator

Move on to Lab 3


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