Loop structures: Difference between revisions
Content added Content deleted
(Added UNIX Shell) |
(→while) |
||
Line 32: | Line 32: | ||
// Don't forget to change the value of condition. |
// Don't forget to change the value of condition. |
||
// If it remains nonzero, we'll have an infinite loop. |
// If it remains nonzero, we'll have an infinite loop. |
||
} |
|||
} |
|||
===do-while=== |
|||
int main (int argc, char ** argv) { |
|||
int condition = ...; |
|||
do { |
|||
// Do something |
|||
// The difference with the first loop is that the |
|||
// code in the loop will be executed at least once, |
|||
// even if the condition is 0 at the beginning, |
|||
// because it is only checked at the end. |
|||
// Don't forget to change the value of condition. |
|||
// If it remains nonzero, we'll have an infinite loop. |
|||
} while ( condition ); |
|||
} |
|||
===for=== |
|||
int main (int argc, char ** argv) { |
|||
int i; |
|||
for {i=0; i<10; ++i) { |
|||
// The code here will be performed 10 times. |
|||
// The first part in the for-statement (i=0) is the initialization, |
|||
// and is executed once before the loop begins. |
|||
// The second part is the end condition (i<10), which is checked |
|||
// every time the loop is started, also the first time; |
|||
// the loop ends if it is false. |
|||
// The third part (++i) is performed every time the code in the loop |
|||
// is at the end, just before the end condition is checked. |
|||
} |
|||
} |
|||
===while with continue=== |
|||
The continue statement allows you to continue execution |
|||
at the beginning of the loop, skipping the rest of the loop. |
|||
In C you can only do this with the most inner loop. |
|||
You can also do this with do-while and for. |
|||
int main (int argc, char ** argv) { |
|||
int condition = 1; |
|||
while ( condition ) { |
|||
// Do something |
|||
if (other condition) |
|||
continue; // Continue at the beginning of the loop |
|||
// Do something else |
|||
// This part is not executed if other condition was true |
|||
} |
|||
} |
|||
===while with break=== |
|||
The break statement allows you to stop a loop. |
|||
In C you can only break from most inner loop. |
|||
You can also do this with do-while and for. |
|||
int main (int argc, char ** argv) { |
|||
int condition = 1; |
|||
while ( condition ) { |
|||
// Do something |
|||
if (other condition) |
|||
break; // Continue after the the loop |
|||
// Do something else |
|||
// This part is not executed if other condition was true |
|||
} |
} |
||
} |
} |