This week you were working on your decoder bots while we talked about Loops in class. Here’s the rundown.
WHILE loop.
This is most basic type of loop. It takes the form:
while ( <boolean expression> ){
//do stuff
}
EXAMPLE:
while(nextToABeeper()){
pickBeeper();
}
The while-loop will execute the block of code as long as the boolean expression evaluates to “true.” The boolean expression can use compound boolean logic as well.
EXAMPLE:
int count = 0;
while(nextToABeeper() && count < 10){
pickBeeper();
count++;
}
It is common that you want to loop over a section of code a specific number of times. When this is the case it is more common to use a for-loop. A for-loop wraps up a counting variable, a loop condition, and how to change the variable in one statement. It takes the form:
for(<var init> ; <loop condition> ; <var change>){
//do stuff
}
EXAMPLE: this example does the exact same thing as the previous while-loop example:
for(int count=0; nextToABeeper() && count < 10; count++){
pickBeeper();
}
The example above is actually not all that common. Usually, a for-loop is a simple design to loop a specific number of times.
You did Lab 8:: Fun with loops to get practice using nested loops. In class I showed the following example which prints an “X” pattern of x’s to the console window:
for(int i=0; i < 10; i++){
for(int j=0; j < 10; j++){
if(i==j || i+j==9)
System.out.println("X");
else System.out.println("_");
}
}
You MUST come to grips with a nested loop, how it works and what it does. Frequently, a nested-loop is used to traverse 2-D structure (like the karel World, or the console window). You use the nested-loop to obtain variables that will have values equal to every possible coordinate pair in the 2D space. In the loop above, for example, think about the values of i and j each time the if-statement is evaluated:
i | j ---|--- 0 | 0 0 | 1 0 | 2 0 | ... 1 | 0 1 | 1 1 | 2 ...etc... 9 | 7 9 | 8 9 | 9
Nested loops are not always used to traverse a 2D structure. For example, many of the sorting strategies we have studied require nested loops.
boolean done=false;
while( !done){ //outer loop goes until 'done' is set to true
done = true; //assume it is done
for( i =0; i<numCards; i++ ) //for each card in the list
if( card[i] > card[i+1]){ // if two need to be swapped, do so
swap(card, i, i+1);
done = false; //if we made a swap we're not done
}
}
}
Leave a Reply