C Language
Looping Statements
FOR - for loops are the most useful type.
Syntax: variable declaration; for ( variable initialization; condition; variable update ) { Code to execute while the condition is true } Example: #include <stdio.h> int main() { int x; /* The loop goes while x < 10, then x increases by one every loop*/ for ( x = 0; x < 10; x++ ) { /* Keep in mind that the loop condition checks the conditional statement before it loops again. consequently, when x equals 10 the loop breaks. x is updated before the condition is checked. */ printf( "%d\n", x ); } getchar(); } WHILE - while loops are very simple. Syntax: variable declaration; while ( condition ) { Code to execute while the condition is true } Example: #include <stdio.h> int main() { int x = 0; /* Don't forget to declare variables */ while ( x < 10 ) { /* While x is less than 10 */ printf( "%d\n", x ); x++; /* Update x so the condition can be met eventually */ } getchar(); } DO..WHILE - DO..WHILE loops are useful for things that want to loop at least once.
Syntax: variable declaration; do { Code to execute while the condition is true } while ( condition ); Example: #include <stdio.h> int main() { int x; x = 0; do { /* "Hello, world!" is printed until x is equal to 9 */ printf( "Hello, world!\n" ); x++; } while ( x !=10 ); getchar(); } |
|
Quick Links |