switch (val){ case 1 : // code here break; case 2 : // more code break; case 3 : //etc. break; default: // default code break; }

This is a much neater form that accomplishes the same goal. After each case, write the value in question followed by a colon and the code you want executed if the variable has this value. The separate break statements are necessary to stop the switch statement; if you leave out a break statement, execution of the code within the switch statement's braces will continue until a break command is reached. In case the value does not match any of the other cases presented, you should always include a default case at the end, as indicated. It's considered good style to break after the default code, although it is not strictly necessary.

Loops

Almost every program will repeat some segment of code in structures called loops. C++ provides three ways to do this: for-loops, while-loops, and do- loops.

For-loops are generally used when it is necessary to increment or otherwise modify a value after every pass. The structure is:

for(<initial values>; <condition to continue looping>; <update, or increment>) { /* code to loop through */ }

The following simple example prints out the numbers 1 through 10:

for(int i = 1; i <= 10; i++) {cout << i << endl;}

Because there is only one line inside the for-loop's braces, the braces could be omitted. The for-loop initializes the value of i to 1, checks the test condition (which is initially true because 1 <= 10), and executes the code inside. After a pass through the loop, i is incremented (i++) and the test condition is checked again. This continues until the test condition is false. Note that the integer variable i is declared inside the for-statement. This is perfectly legitimate, but once the for-loop is finished, the variable i will no longer exist. Its scope is confined to the for-loop.

While-loops are much like for-loops, except that there is no initial value assignment or updating of variables. While-loops only check the condition before every pass:

while(<condition to keep looping>) { /* code goes here */ }

Do-loops are almost equivalent to while loops, except that they will necessarily execute the code in brackets at least once before breaking:

do { /* code here */ } while (<condition to keep looping>);

The test condition of a do-loop will not be checked until after the first pass through the loop.

In any kind of loop, the execution of a break command will halt the looping. Execution of a continue command will send the execution back to the top of the loop; and, in the case of for-loops, will also carry out the incrementing and updating.