Reputation:
I'm trying to translate the following for loop into a while and a do-while loop, but for some reason the code breaks before it ever gets into the actual loop.
Here's what I'm trying to replicate:
#include <stdio.h>
int main(void)
{ int y;
for (y=1;y<10; y++)
{ if (y == 5)
continue;
printf("%2d", y);
}
printf("\ny=%2d\n",y);
return 0;
}
Here are my attempts at making equivalent while and do-while loops:
#include <stdio.h>
int main(void)
{
int y;
y = 1;
while(y < 10) // here's my while loop
{
if(y == 5)
continue;
printf("%2d", y);
y++;
}
printf("\ny=%2d\n",y);
/********************
... and my do-while
********************/
y = 1;
do
{
if (y == 5)
continue;
printf("%2d", y);
y++;
} while(y < 10);
printf("\ny=%2d\n",y);
return 0;
}
Where did I go wrong?
Upvotes: 2
Views: 89
Reputation: 72737
In a for
loop, continue
jumps to the third expression of the for
statement, which increments the counter.
In a while
loop, continue
jumps to the next iteration immediately, skipping the increment.
Upvotes: 5
Reputation: 11489
If the condition is met in your code, you don't increment the variable and so you get stuck in an infinite loop. Try
#include <stdio.h>
int main(void)
{
int y;
y = 0;
while(++y < 10) // here's my while loop
{
if(y == 5)
continue;
printf("%2d", y);
}
printf("\ny=%2d\n",y);
or the like.
Upvotes: 3