Multiple Control Statements

From CompSciWiki
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 loop or a while loop to exit before the count has reached its 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 create 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 the 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 

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 terminate when one of the conditions is met. In the example above, the loop will exit after its fifth (0+1+2+3+4 = 10) iteration.


Summary: Multiple control statements can be used when you have more than one instance where the loop should either continue to iterate, or cease to iterate. Using multiple control statements also allows code to be shortened, sometimes significantly. For example, instead of having multiple if statements in a loop, you may want to put the conditions contained in the if statements into a multiple control statement in a loop. Doing this may allow you to write less code and will also make your code more readable.

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