C Loops
Loops
Loops are used to repeat a block of code. A loop lets you write a very simple statement to produce a significantly greater result simply by repetition.
Example 1
#include <stdio.h> #include <stdlib.h> int main() { int forX = 0; int whileX = 0; int doX = 0; /* The loop goes while x < 10, and x increases by one every loop*/ for ( forX = 0; forX < 10; forX++ ) { /* Keep in mind that the loop condition checks the conditional statement before it loops again. consequently, when x equals 10 the loop breaks. forX is updated before the condition is checked. */ printf( "%d\n", forX ); } while ( whileX < 10 ) { /* While whileX is less than 10 */ printf( "%d\n", whileX ); whileX++; /* Update whileX so the condition can be met eventually */ } do { /* "Hello, world!" is printed at least one time even though the condition is false*/ printf( "%d\n", doX ); } while ( doX != 0 ); getchar(); }
Break, Continue
The break command will exit the most immediately surrounding loop regardless of what the conditions of the loop are. Break is useful if we want to exit a loop under special circumstances.
Example 2
#include <stdio.h> #include <stdlib.h> int main() { int forX = 0; int whileX = 0; int doX = 0; /* The loop goes while x < 10, and x increases by one every loop*/ for ( forX = 0; forX < 10; forX++ ) { if(forX == 5) break; printf( "%d\n", forX ); } getchar(); }
page_revision: 0, last_edited: 1206020635|%e %b %Y, %H:%M %Z (%O ago)





