|   Control Statements | ![]() |
if StatementsStatements may be grouped using “{” and “}” and may contain the regular C if statement, or the if-else statement in the form “if ( <condition> ) <statement> [ else <statement> ]”. For example: if ( x < 5 ) x = 0;or if ( y > x ) max = y;
for StatementsThe standard C for statement can be used in the form “for ( <initialization expression>; <expression>; <expression> ) <statement>” and work the same way as in C++. For example: for ( int i = 0, x = 0; i < 15; i++ ) {
while, do-while StatementsThe while and do-while statements can also be used in the form “while ( <condition> ) <statement>” or “do <statement> while ( <condition> )” and work the same way as in C. For example: while ( myVar < 15 ) {x *= myVar; myVar += 2; } or do {
switch StatementsA switch statement can be used to compare a variable with a number of values and perform different operations depending on the result. switch statements are of the form “switch ( <variable> ) { case <expression>: <statement>; [break;] ... default : <statement>; }” and works the same way as in C. For example: switch ( value ) {
break and continuebreak or continue can be used using the syntax “break;” or “continue;”. Use break to exit out of the current for, switch, while, or do block and transfer program control to the first statement after the block. Use continue to jump to the end brace of any for or while loop and continue execution of the loop. These work the same way as they do in C. |
Copyright © 2006 Shawn (L. Spiro) Wilcoxen |