Loops: Lesson - Continuing in C

Hello,

In the lesson: https://www.codecademy.com/courses/learn-c/lessons/loops-c/exercises/continuing

The first part of the exercise says to:
Use continue to make the while loop skip the print statement for when i == 5.

I did it like this:

#include <stdio.h>

int main() {
  int i = 0;
  while(i < 10) {
    // Figure out how to skip the print of 5 here
    i++;
    if (i == 5) {
      continue;
    }

    printf("%d\n", i);
  }
}

and it prints from 1-10 excluding 5 but it should have been 0-9 excluding 5.
can someone guide me as to what I am missing here?

i is initialized as 0 which is good.

But in your while loop, the very first statement is i++;

In the first iteration of the loop, i starts off being 0, but in the very first statement of the loop it is incremented to 1. So the first value printed is 1.
Similarly in the last iteration where i starts off being 9, i is incremented to 10 within the loop and then printed.

If you want to print 0-9 (excluding 5), then the increment should come after the print statement. So i++; should be moved to the bottom of the loop below the printf. But, there is a complication to consider. If we move the i++; to the bottom, then we will get stuck in an infinite loop. Because, when i is 5, the condition if (i == 5) will be true and we will continue to the next iteration. But i is still 5, so in the next iteration we will continue again. And again and again and …

Can you think of a way to handle i being 5 properly to avoid the infinite loop?

Hint

The if block can have more than one statement. Can you think of a statement which you can add within the if block but before continue?


Spoiler code
#include <stdio.h>

int main() {
  int i = 0;

  while(i < 10) {

    if (i == 5) {
      i++;
      continue;
    }
    
    printf("%d\n", i);
    i++;
  }
}
1 Like