Additional Information

From CompSciWiki
Jump to: navigation, search

COMP 1010 Home > Loops


Introduction

Here we will discuss some useful ways loops can be enhanced to be more efficient and suited to particular tasks. Three topics will be covered including multiple control statements, do-while loops, and running totals / sentinel values. These additions to your skills with loops will allow you to write more effiecient code as well as code that is more reliable and readable.

   

{{{Body}}}


Do-While Loops

Do-while loops are a bottom tested loop. They are used if you need to execute a section of code one or more times. Since you typically want to execute a section of code zero or more times, a while loop is strongly preferred. Using a do-while loop improperly can corrupt your data, so use it with caution. Below is the syntax for a Do-While loop. As you can see, the condition is only tested after the code in the loop has been executed once. As well, notice the required semi-colon after the 'while(condition)'.

do
{

     // statements

} while( condition );

Summary

More complex structures and problems can be solved using these types of methods. Sentinels and Multiple Control Statements allow us to make much more efficient code. Using these methods we can evaluate more data at once. Do-while loops are useful if the block of code must be executed once. A for loop may require more than one control variable to execute so having multiple control variables is the only way to do that.