![]() |
![]() |
|
![]() |
|
Section 4: Looping. Looping in C++ can be accomplished in three different ways. For loops repeat a specific number of times, while loops repeat while a given condition is true, and do...while loops do the same thing except they are guaranteed to be executed once. Note: Remember that true in C++ is not just 1. Any non-zero value is true!
For loops A for loop is defined as follows: for(variable=startingvalue;a condition that remains true until the variable reaches a certain value;an increment or decrement value) { statements; } While that is a basic example, let's use a better example. //Note that I declare the variable i inside the for loop. This is only legal in C++. short j=0; for(short i =0;i<5;i++) //While i is less than 5 the code will loop starting at i=0. { j++; } Note that it is very easy to create an infinite loop by just stating for(;;). This is legal, but not useful. Also, if you do not use braces in a for loop, the loop will execute the statement immediately after the for loop. While loops A while loop is defined as follows: while(conditionthatistrue) { statements; } To get out of a while loop, you need to make the condition that is true in the while loop false. This idea is important in making menus where a variable is polled for a certain value to get it out of a program. Do...While Loops A do... loop is defined as follows: do { statements; }while(conditionthatistrue); Remember that a semi-colon is required at the end of the do...while loop. Break and Continue There are two statements that, when inserted into a loop affect it. If you insert break; into the inside of a loop, the loop will terminate no matter what. If you insert continue; into the interior of a loop, the loop will continue onto the next iteration. |
||
![]() |
Binary Central by Anman: "http://www15.brinkster.com/anman/" |
![]() |