Multiple Control Statements

From CompSciWiki
Revision as of 12:21, 7 December 2011 by DavidHo (Talk | contribs)

Jump to: navigation, search

COMP 1010 Home > Loops


Introduction

Loops can be used with more than one test condition. This allows a loop such as a for or while loop to exit before the count has reached it's end case. This is useful to increase the efficiency of your code. Consider you are searching an array for a specific integer. Instead of searching the whole array to find it, you can crate a boolean variable, called a flag, to tell you if the integer has been found. When the value you are looking for is equal to the current value in the array you can set you flag to true. A condition statement such as "!found" (not found) makes the code readable and the intent of the variable obvious.


Example 1:


boolean flag1 = true;
boolean flag2 = false;
boolean flag3 = true;

while(flag1 && (flag2 || flag3)) //continue while flag is true AND either of flag2 or flag3 is true
{
    // do stuff
}


Example 1 above shows the syntax of using multiple control statements with a while loop. The boolean values, flag1, flag2, flag3, can be substituted for any boolean expression. For this example you can see that the loop will exit only when either flag1 is false or both flag2 and flag3 are false. As with if statements, the control statements are checked from left to right. For example if you have:


Example 2:

Note: This example requires the knowledge of arrays.

int[] array = {0,1,2,3,4,5,6,7,8,9};  // Array of 10 integers
int sum = 0;  // Sum of integers in array

// Loop through the array until sum is greater than or equal to 10.
for ( int i = 0 ; i < array.length && sum < 10 ; i++ )
{
     sum += array[i];
}

System.out.println("The sum is: " + sum);


See the "sum < 10" in the condition of the for loop. This is the second control statement and will be checked the same way as an if statement. The loop will exit when one of the conditions is met. In the example above the loop will exit after its sixth (0+1+2+3+4+5 > 10) iteration. Using multiple control statements can also be used with while loops.

Previous Page: Infinite Loops Next Page: Running Totals and Sentinel Values