Search code examples
cif-statementfor-loopbreakcontinue

Why is this program giving no output?


I have a program which is not working due to a for loop in it. I'm pasting a working snippet of code here:

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

int main()
{
    int numLoop = 19;
    int counter;
    int maxloops = 25;
    int takenNum1 = 9, takenNum2 = 14, takenNum3 = 17, takenNum4 = 21, takenNum5 = 24;

    for (counter=1; counter==maxloops; counter++)
    {
        printf("%d \n", counter);

        if (counter == numLoop)
        {
            break;
        }

        if (counter == takenNum1 || counter == takenNum2 || counter == takenNum3 || counter == takenNum4 || counter == takenNum5)
        {
            counter++;
            continue;
        }
    }

    return 0;
}

The expected output is: 1 2 3 4 5 6 7 8 10 11 12 13 15 16 18 19

Nothing is being printed.


Solution

  • The for loop condition appears buggy. You want to write counter != maxloops instead of counter==maxloops.

    Otherwise, the loop condition is not met and the loop body is not at all executed.

    That said, as per your requirement,

    1. you need to move the checking block

      if (counter == takenNum1 || counter == takenNum2 || counter == takenNum3 || counter == takenNum4 || counter == takenNum5)
      {
          counter++;
          continue;
      }
      

      before the printf() statement to avoid unconditional printing.

    2. The for loop condition should really look like

      for (counter=1; counter < numloop; counter++)
                               ^^^^^^^^^^
      

      as you want the output to be limited to 19.