28 October 2012

Part 6 - While and For Loops

Topics Covered:

While loops
Loop conditions and "forever" loops
The "for" loop

Watch video >>

Downloadable files





1. Modify the program countchars.c from Part 5 to use a for loop instead of a while loop.

2. The program  sequence LOW HIGH  should print all the integers from LOW to HIGH inclusive, with each integer on its own line. Use the downloadable source provided above (sequence.c) as a starting point, and fill in the needed portion of the program so that it operates as described. Compile the program using the following command:

gcc -Wall -std=gnu99 -o sequence.exe sequence.c

The option -std=gnu99 (or, alternatively -std=c99) tells the compiler to use C99 language features. One of these features is the ability to declare variables like `int i=0' inside the first part of the for loop.


1. The C Standard defines an int to be minimally 16-bits or 32-bits wide, but it could be wider depending on the machine. If you want an integer which is exactly 32 bits, use int32_t instead of int. For a 32-bit unsigned integer, use uint32_t. This type of integer can represent any nonnegative value in {0, 1, 2, ..., 232-2, 232-1}. With this in mind, consider the program zot.c, which is defined as follows:

#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>

int main(int argc, char*argv[])
    if (argc < 2) {
        printf("Usage: zot N\n");
        return 1;
    int N = atoi(argv[1]);
    for (int i=0; i < N; i++)
        for (register uint32_t j=1; j != 0; j++)
    return 0;

The keyword register means that we want the variable j to be stored in a CPU register, which is many times faster than storing it in memory. Compile with the following command:

gcc -Wall -std=gnu99 -O0 -o zot.exe zot.c

Normally, the compiler tries to optimize loops by automatically assigning CPU registers. The -O0 (``dash Oh zero'') tells gcc not to do this; in this example we want to decide that for ourselves.

a. Try to run zot on your machine with small values of N. How long does it take before Zot! is printed?

b. Based on the way the loop condition (j != 0) is defined, it seems like Zot! should never appear. Explain why it does. What happens when the result of an (unsigned) integer operation is too large to fit inside the variable?

No comments:

Post a Comment