-2

This is the program:

#include<stdio.h>

int main()
{
    int i=(-5);
    while(i<=5){
        if (i>=0){
            break;
        }
        else{
            i++;
            continue;
        }
        printf("hello\n");
    }
    return 0;
}

My question is, why does 'hello' not get printed at all?

BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
  • 1
    [When in doubt, read the documentation](http://port70.net/~nsz/c/c11/n1570.html#6.8.6.2) – ad absurdum Sep 12 '17 at 16:03
  • Run your program step-by-step in a debugger. Also read [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – Thomas Fritsch Sep 12 '17 at 18:25

4 Answers4

1

Because you have used continue incorrectly. It basically stops the line that is after it and goes to the condition checking part of the while loop. That's why it doesn't print hello.

From standard $6.8.6.2

A continue statement causes a jump to the loop-continuation portion of the smallest enclosing iteration statement; that is, to the end of the loop body.

user2736738
  • 30,591
  • 5
  • 42
  • 56
0

You have a single if else statement. Everything that happens inside that loop will happen inside the if or the else. In your particular case, it will execute the else statement until 'i' is 0(the continue makes it so that it goes back to the loop condition, but in your case the continue is completely unnecessary because it's the last statement in the else), then it will execute the if and break out of the loop

savram
  • 500
  • 4
  • 18
0

Stepping though the loop, we have

1st pass i == -5, if condition false, else branch taken, i incremented to -4, continue to start of while loop

2nd to 4th pases same for i == -4 to i == -2

5th pass i == -1, if condition false, else branch taken, i incremented to 0, continue to start of while loop

6th pass i == 0, if condition true, break from while loop, return 0 from main

Neither of the if branches cause the flow to pass through the printf line.

Paul Floyd
  • 5,530
  • 5
  • 29
  • 43
0

The reason why printf() statement will never execute is because you had break statement in if and continue statement in else. Both statement are useful to break or skip the flow of execution of program.

Click here to learn when to use those statements.

Now, here i is initialized with -5. So until i reaches the value 0, else() part of the code will be executed. Else has continue statement, that will skip all the following statements and start next iteration. So, printf() statement will be skipped every time.

Once i will be incremented up to 0,if() part of code will be executed. If() has break statement that will break the loop and execution of the program will be over by main() returning 0 as there are no more statements following loop other than return 0.

Hope it'll be helpful.

Harshil Doshi
  • 3,497
  • 3
  • 14
  • 37