Skip to main content
Logo image

Section 16.2 Debugging Code

The next thing that happens once you write more complicated programs, is that you make mistakes ("bugs"). You therefore need strategies to "debug" your program.
If you program compiles and runs but doesn’t do what you had intended for it to do then one great strategy is to sprinkle your code with printf() statements that leave a trail of how the program executes and allow you to track the values of important variables along the way. This strategy makes it easier to pinpoint where in your code things are starting to go wrong.

If you cannot see this codecast, please click here.

Check Your Understanding Check Your Understanding

1.

Which of the three printf() statements in the code below is the most useful in debugging this faulty loop?
#include <stdio.h>
int main(void)
{
  int N, i, sum;
  printf("Good Morning!\n"); /* printf() statement #1 */
  i=1;
  N=10;
  sum=0;
  while (i <= N) {
    printf("i = %d, sum = %d.") /* printf() statement #2 */
    sum += N;
    i--;
  }
  printf("The sum from 1 to %d equals %d.\n", N, sum); /* printf() statement #3 */
  return(0);
}
  • printf() statement #2
  • Correct
  • printf() statement #1
  • Not quite. Try again!
  • printf() statement #3
  • Not quite. Try again!

2.

You want to add up the numbers from 0 to 9 and write the following code to do so. What (if anything) is wrong with this code?
int i;
int sum=0;
for (i=0; i<10; i--) {
  sum = sum+i;
}
printf("The sum of the number from 0 to 9 equals %d\n", sum);
  • The instruction i-- should be i++
  • Correct
  • There is nothing wrong with this code.
  • Not quite. Try again!
  • One needs to use a while-loop here instead of a for-loop.
  • Not quite. Try again!
  • The variable i needs to be initialized.
  • Not quite. Try again!