<-- back to index...

Keunwoo Lee : CSE 142 : 28 October 1999

Note: We spent most of the class doing the NAW server session 1 exercise. I actually skimmed over most of the following.

for loops:

    index = 0;
    while (index < MAX) {
        /* do stuff here */
        index++;
    }
    /* The following is equivalent to the above: */
    for (index = 0; index < MAX; index++) {
        /* do stuff here */
    }
    

We generally use for when we know the start and end values ahead of time.

  1. Design a for loop that computes the sum of first 100 even numbers.
  2. Which kind of loop (while or for) is more appropriate in the following situations?

switch/case:

    switch (value) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 9:
            printf("value is odd!");
            break;
        case 0: case 2: case 4: case 6: case 8:
            printf("value is even!");
            break;
        default:
            printf("value is not an integer between 0 and 9!");
    }
    

Very important note: Always remember the break statement.

DeMorgan's Laws

  1. !(A || B) == !A && !B
  2. !(A && B) == !A || !B

Try thinking about it in English: the statement, "It is not sunny OR rainy" is equivalent to "It is not sunny, AND it's not rainy either". This corresponds to the first statement above.

Debugging techniques

Diagnostic print statements: Put temporary printf statements in your code to dump the values of variables to the screen at critical points. Good places to put printf statements:

Use the debugger. Learn to use the debugging facilities provided by your environment. Try setting breakpoints halfway through your program; if the program works fine up to the breakpoint, move the breakpoint to a spot 3/4 of the way through, and so on.

Comment out code. Put comments (or if (0) statements) around chunks of code to prevent them from executing. See how this affects the behavior of your program. If everything else works okay, you know where the problem is.

Stop typing. Stop messing around with your code. Step back and think about what your code is doing, where the problems might be.

The overall theme of most debugging strategies is to decrease the amount of code you have to think about at once. Narrowing down the possible sources of the bug is half the battle.


Keunwoo Lee
Last modified: Wed Dec 1 15:15:26 PST 1999