Jump to content
xisto Community
Ahsaniqbalkmc

C Programming: Difference In Behavior Of For And While Loops With Continue Statement

Recommended Posts

So after a gap of many days, I opened the C programming book that I am using to learn C. I learned about while loops, for loops, the switch statetement, the do-while loop and the break and conitune statement.

 

I understood almost everything that I read today. I said almost because I couldn't understand one thing. It is related to the difference in behaviour of FOR loops and WHILE loops when a continue statement is used withing these loops.

 

The book I am reading has given an example where continue statement is used within a for loop. It is a simple loop which starts with the initial value of x = 1 and then runs until x is greater than 10, each time incrementing the value of x by 1. In the body, all it does is prints the value of x. It looks something like this:

for (x=1; x<=10; x++) {   printf("%d", x);}
In this simple FOR loop, the author has put a continue statement withing an IF condition, which interprets as if x is equal to 5 then continue.

So the overall loop becomes:

for (x=1; x<=10; x++) {   if (x==5) {	  continue;   }   printf("%d", x);}
The output of this program (with continue statement) is:

1 2 3 4 6 7 8 9 10
It is clear the when the contidion "X IS EQUAL TO 5" is true the printf statement is skipped.

 

Upto this point everything is clear. But then the author mentions why WHILE loop is different and this is what I don't understand. The words of the author are quoted as:

Earlier, we said that the while statement could be used in most cases to represent the for statement. The one exception occurs when the increment expression in the while statement follows the continue statement. In this case, the increment is not executed before the repetition-continuation condition is tested, and the while does not execute in the same manner as the for.

 

This is what I don't understand. Can somebody explain to me what is the author trying to say.

Share this post


Link to post
Share on other sites

You should also write the same program with the "while" variant, and try a "paper" execution, and you will see the difference."for" gives a list, exactly like the shell statement "for i in apple, bread, banana""while" is a logical condition, like the "while true", which will continue as long as it's true.This will give a difference in the behavior inside a loop and could make one step be performed or not.

Share this post


Link to post
Share on other sites

Hi Ahsaniqbal111,

 

I will try to explain the author with code and breaking it down.

 

Earlier, the author said that the while statement could be used in most cases to represent the for statement.

This code closely matches the for statement except I suggest you do not test/run it. but rather just try to understand it by looking at it, else you'll need to press CTRL+C to break from it.

 

#include <stdio.h>int main(void) {    int x = 1;        while(x <= 10) {        if(x == 5) {            continue;        }        printf("%d ", x);        x++;    }    return 0;}

The one exception occurs when the increment expression in the while statement follows the continue statement.

As you can see in above code, the increment expression in this while loop goes after the continue statement.

 

The increment is not executed before the repetition-continuation condition is tested

Now the problem is that when x = 5 continue will be called meaning we skip the increment expression. That is because continue skips the rest of the code below. This means x will stay 5 and not increment, we will always enter the if statement and the loop will never complete so it will run forever.

 

and the while does not execute in the same manner as the for

This is a different behaviour to the for statement.

 

So this is why your increment, if it's required to exit the loop should come before any continue statement in the loop, but then you would need to change your code to reflect it.

 

So I've written how it could be written below.

 

#include <stdio.h>int main(void) {    int x = 0;        while(x <= 9) {        x++;        if(x == 5) {            continue;        }        printf("%d ", x);    }    return 0;}

So in this above code, I have assigned 0 to x, I have changed the while condition lowering it by 1. I have shifted x being incremented above the continue statement. This now reflects the same answer as the for statement, but does not really reflect how the for statement works.

 

There is another, easier method than lowering the variable and condition and shifting the increment above continue. Again this represents the same output, but not the same flow of the for statement.

 

#include <stdio.h>int main(void) {    int x = 1;        while(x <= 10) {        if(x == 5) {            x++;            continue;        }        printf("%d ", x);        x++;    }    return 0;}

The only difference is I've added an increment inside the if block. As long as it's before continue it will too work.

 

I hope you can understand this. If not, feel free to ask more.

 

 

Cheers,

 

 

MC

Share this post


Link to post
Share on other sites

You should also write the same program with the "while" variant, and try a "paper" execution, and you will see the difference.

Well I changed the program and used the WHILE statement instead of the FOR (and also made other necessary changes for proper execution of the while loop). But instead of just relying on paper execution, I ran the program within eclipse. The result was NOTHING. The console was completely empty and it didn't print out even a single value of x.
I am assuming this is the way how eclipse handles infinite loops.

@mastercomputers, thanks for the great step by step explanation. I now completely understand (or at least think so) the difference.

But can you please throw some light on why the console was completely empty and didn't even show a single value of x. I was expecting the values before X == 5 to be printed normally and then something strange to happen. Is it the way how eclipse handles infinite loops?

Share this post


Link to post
Share on other sites

Hi Ahsaniqbal111,I do not know which code you are using, so if you could show it that would greatly help.I am not sure how Eclipse handles infinite loops. It's possible it will time out after it's been running in circles but either way, it should not be handling these things for you without notifying you what it did. So, see if Eclipse has logs, or errors when you run the program. If it does not, then you would have a hard time understanding what Eclipse does for you and what your program actually does. That's one of the reasons I don't rely on IDEs that can take over your program.Lets see the code you used and I'll try it on Eclipse myself and see if I can tell what it's doing.Cheers,MC

Share this post


Link to post
Share on other sites

The code I had used is:

#include <stdio.h>int main(void) {int x = 1;while (x <= 10) {  if (x == 5) {   continue;  }printf("%d", x);x++;}return 0;}
As far as my understanding is concerned, I should have got values 1, 2, 3, 4 just fine. The trouble should have started when x becomes equal to 5. However, there is no output in the console so it must have something to do with eclipse.

Before eclipse, I was manually doing all the compiling and editing in separate programs. The setup was that I would first use a text editor like "kate" to create a program. Then I would open up a terminal window and manually edit the GCC command to compile the program. And then enter the command to run the program.

With eclipse, the overall process is extremely specified. There is a very sophisticated text editor window with great error notifying features. Thus the number of syntax errors in programs basically reduces to 0. Then after the program is created, all i do is press ctrl+b to build the program. If there are errors in the program that I might have missed, I get notified about here. After building is complete, I just press ctrl+f11 and the program runs in the console. So everything is done without ever having to leave the eclipse window or without the need of any additional program. It saves quite a lot of time, but more importantly it saves me stamina that is just eroded by repetitions of gcc commnads in the terminal windows.

So over all, I am very happy using eclipse, but I need to know why the output of this program is not according to my expectations.

Share this post


Link to post
Share on other sites

Hi Ahsaniqbal111,

 

Well the only way I could explain this is that stdout (console) has a buffer and will not be printed until either the buffer is filled, has been flushed or it encounters a newline but only for terminal, doesn't flush if being written to a file.

 

So what you are expecting is correct, except it's only in the buffer and that you're stuck in the infinite loop which isn't going to add anymore to the buffer. This means you won't get any output due to the buffer holding the information.

 

You can either put setbuf(stdout, NULL); at the start of your main function to turn the buffer off, or you can fflush(stdout); after your printf call, or you can fprintf(stderr, "%d ", x); as stderr does not have a buffer.

 

 

Cheers,

 

MC

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.