C:Loops - The Break And Continue Statement
(Page 4 of 4 )
Sometimes you may wish to break out of a loop even if the criteria has not been met to end the loop. Similarly you can force a program to reiterate a loop from the start, skipping over the elements of the loop following the Continue statement. Break also breaks out instantly from a loop, not bothering to carry out the rest of it. Here is an example with an infinite loop that counts to ten, then a continue forces it to count to 11, even though the break should (and eventually does) break out of the loop. Here it is:
#include <stdio.h>
int main()
{
int x=0;
for(;;)
{
x++;
if(x<=10)
{
printf("%d, ",x);
continue;
}
printf("%d is greater than 10 fool!n",x);
break;
}
return(0);
}
Here is the result of this program:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 is greater than 10 fool!
<Note: The for(;;) creates an infinite loop>
Conclusion
We didn't cover everything in this tutorial related to loops, such as nesting loops, but we did cover a lot of ground and will hopefully explain things in more detail further down the pipe. For now though you should have a good place to start on your programming. I'll be posting more articles in this series in the near future, so be sure to check back often. Thanks.
Till then...
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |