Loops

It would be completely reasonable to ask what loops have to do with programming. But they are exactly what the name implies. They are a way of repeating the same part of the code more than once or looping over the same part of code although potentially for a different outcome each time.

This can simply mean doing the same thing until the code being looped over (iterated) prompts the loop to end. It could be a predetermined number of iterations as specified by the loop code itself or it might be until a predetermined situation or condition is met. Or it could be a combination of more than one of these things. Along with if, else, and switch, which we will learn about in the next chapter, loops are part of the Java control flow statements.

Here we will learn how to repeatedly execute portions of our code in a controlled and precise way by looking at diverse types of loops in Java. Think about the conundrum of drawing all the grid lines in the Sub' Hunter game. Repeating the same code over and over could be very useful for drawing dozens of lines on the screen without writing dozens of repetitive lines of code.

The types of loops include while loops, do while loops and for loops. We will also learn the most appropriate situations to use the different types of loops.

We will look at all the major types of loops that Java offers us to control our code and we will use some of them to implement a working mini-app to make sure we understand them completely, then we can add some code to take advantage of loops in the Sub' Hunter game. Let us look at the first simplest loop type in Java called the while loop.

While loops

Java while loops have the simplest syntax. With the while loop, we put an expression that can evaluate to true or false. If the expression is true, the loop executes. If it is false it doesn't. Take a look at this code:

int x = 10;

while(x > 0){
   x--;
   // x decreases by one each pass through the loop
}

What happens here is this: Outside of the while loop an int named x is declared and initialized to 10. Then the while loop begins. Its condition is x > 0. So, the while loop will continue looping through the code in its body until the condition evaluates to false. So, the code above will execute 10 times.

On the first pass x = 10 then 9 then 8 and so on. But once x is equal to 0, it is of course no longer greater than 0, the program will exit the loop and continue with the first line of code after the while loop.

It is important to realize that it is possible that the while loop will not execute even once. Take a look at this.

int x = 10;

while(x > 10){
   // more code here.
   // but it will never run 
   // unless x is greater than 10.
}

Moreover, there is no limit to the complexity of the conditional expression or the amount of code that can go in the loop body.

int lives = 3;
int aliens = 12;

while(lives > 0 || aliens > 0){
   // keep playing game
   // etc.
}

// continue here when lives and aliens equal 0

The above while loop would continue to execute until both lives and aliens were equal to or less than zero. As the condition uses logical OR operator || either one of those conditions being true will cause the while loop to continue executing.

It is worth noting that once the body of the loop has been entered it will always complete even if the expression evaluates to false, part way through, as it is not tested again until the code tries to start another pass. For example:

int x = 1;

while(x > 0){
   x--;
   // x is now 0 so the condition is false
   // But this line still runs
   // and this one
   // and me!

}

The above loop body will execute exactly once. We can also set a while loop that will run forever; called an infinite loop. Here is one.

int x = 0;

while(true){
   x++; // I am going to get mighty big!
}

The keyword true unsurprisingly evaluates to true. So, the loop condition is met. We need an exit plan.

Breaking out of a loop

We might use an infinite loop like this next code so that we can decide when to exit the loop from within its body. We would do this by using the break keyword when we are ready to leave the loop body. Like this:

int x = 0;

while(true){
   x++; // I am going to get mighty big
   
   break; // No you're not
   // code doesn't reach here
}

We can combine any of the decision-making tools like if, else, and switch within our while loops and all the rest of the loops we will look at in a minute. Here is a sneak look ahead at the if keyword. For example:

int x = 0;
int tooBig = 10;

while(true){
   x++; // I am going to get mighty big!
   if(x == tooBig){
      break;
   } // No, you're not ha-ha.
   
   // code reaches here only until x = 10
}

You can probably work out for yourself that the if(x == tooBig) line of code causes the break statement to execute when x equals tooBig.

It would be simple to go on for many more pages showing the versatility of while loops but at some point, we want to get back to doing some real programming. So here is one last concept combined with while loops.

Do while loops

A do while loop is very much the same as while loops with the exception that a do while loop evaluates its expression after the body. This means that a do while loop will always execute at least once before checking the loop condition

int x= 10000000;// Ten million
do{
   x++;
}while(x < 10);
// x now = 10000001 

The code will execute the contents of the do block (x++), once, before the while condition is tested even though the condition evaluates to false.

Note

Note that break can also be used in do while loops.

Let's look at one more type of loop before we get back to the game.

For loops

A for loop has a slightly more complicated syntax than while or do while loop as they take three parts to initialize. Have a look at the code first then we will break it apart.

for(int i = 0; i < 10;  i++){

   // Something that needs to happen 10 times goes here

}

The apparently obscure form of the for loop is clearer when put like this:

for(declaration and initialization; condition; 
change after each pass through the loop).

To clarify further we have:

  • Declaration and initialization: We create a new int variable i and initialize it to zero.
  • Condition: Just like the other loops, it refers to the condition that must evaluate to true for the loop to continue.
  • Change after each pass through the loop: In the example i++ means that 1 is added/incremented to i on each pass. We could also use i-- to reduce/decrement i each pass.
    for(int i = 10; i > 0;  i--){
       // countdown
    }
    // blast off i = 0

Note

Note that break can also be used in for loops.

The for loop essentially takes control of initialization, condition evaluation and the control variable on itself.

Nested loops

We can also nest loops within loops. For example, take a look at this next code.

int width = 20;
int height = 10;
for(int i = 0; i < width; i++){
   for(int j = 0; j < height; j++){
      // This code executes 200 times
   }
}

The previous code will loop through every value of j (0 through 9) for each and every value of i (0 through 19).

The question is why would we do this? Nesting loops is useful when we want to perform a repetitive action that needs the changing values of two or more variables. For example, we could write code like the above to loop through a game board that is twenty spaces wide and ten spaces high.

Also note that loops of any type can be nested with any other loop. We will do this in most of the projects in this book.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.248.239