Lesson #1-14: Introduction to Loops
In the previous lessons, we discussed conditional statements (such as the if statement) that carry out an appropriate response depending on the condition satisfied.
We will now begin covering loops, which are also often conditionally executed.
First, what is a loop? Well, as the name suggests, loops refer to code that is executed multiple times.
When is a loop useful?
A very simple scenario: if you wanted to output a specific line of text a hundred times.
One solution to this would be to copy and paste the System.out.println(...) statement 100 times.
This is not very efficient for both the programmer and the computer.
Instead, the proper solution would be to utilize a loop and a counter to execute one line of System.out.println(...) 100 times.
A more practical (and relevant) example is the game loop. We will have a hefty discussion about this crucial loop later, but here's a little preview of what is coming.
You will soon discover that games are very mechanical in nature. Behind the fancy graphics and beautiful sounds, there is a "heart" that causes the game to "update" its contents (move all in-game objects to the new location based on their velocity) and to render the graphics (re-draw the objects in the newly defined location). The game loop is the closest thing to this heart.
Like I said before, loops tend to be conditional. The game loop is too.
Here's an example of a fake game loop.
In the previous lessons, we discussed conditional statements (such as the if statement) that carry out an appropriate response depending on the condition satisfied.
We will now begin covering loops, which are also often conditionally executed.
First, what is a loop? Well, as the name suggests, loops refer to code that is executed multiple times.
When is a loop useful?
A very simple scenario: if you wanted to output a specific line of text a hundred times.
One solution to this would be to copy and paste the System.out.println(...) statement 100 times.
This is not very efficient for both the programmer and the computer.
Instead, the proper solution would be to utilize a loop and a counter to execute one line of System.out.println(...) 100 times.
A more practical (and relevant) example is the game loop. We will have a hefty discussion about this crucial loop later, but here's a little preview of what is coming.
You will soon discover that games are very mechanical in nature. Behind the fancy graphics and beautiful sounds, there is a "heart" that causes the game to "update" its contents (move all in-game objects to the new location based on their velocity) and to render the graphics (re-draw the objects in the newly defined location). The game loop is the closest thing to this heart.
Like I said before, loops tend to be conditional. The game loop is too.
Here's an example of a fake game loop.
while (playerAlive == true){
updateGame(deltaTime);
renderGame(deltaTime);
}
In this example of the while loop, if the condition playerAlive == true is satisfied, the updateGame() method and the renderGame() method will be executed.
The updateGame() method will handle things like collision or physics, while renderGame() method will display the characters and environment in the current location.
I added a deltaTime parameter to the methods, which is typically the number of nanoseconds that have passed since the previous execution of the loop. I'll explain why, although this might not have any meaning to you until you actually start game programming.
Processors, especially those found on modern mobile devices, are erratic; the speed at which the loop is executed varies.
Why is this a problem? Let's say that updateGame() method moves a character right by 5 pixels. Now consider what would happen if updateGame() was not run at equal intervals. If the game slowed down and the loop took double the amount of time to execute again, the character would move at half speed. This would be disastrous for even a simple game like Temple Run.
So what a lot of game developers do is this. Instead of moving 5 pixels, the character would move 5 pixels MULTIPLED BY the amount of time that elapsed since the last execution of the loop (which we can define as deltaTime). This means that no matter how much the processor slows down, the character will always travel at the same speed.
Enough with the theory. Let's meet the first loop!
Lesson #1-15: The While Loop
We saw a quick example of a while loop above. Let's discuss it in a little more depth.
The while loop will continue to execute as long as the condition is satisfied.
Take a look at this example:
The updateGame() method will handle things like collision or physics, while renderGame() method will display the characters and environment in the current location.
I added a deltaTime parameter to the methods, which is typically the number of nanoseconds that have passed since the previous execution of the loop. I'll explain why, although this might not have any meaning to you until you actually start game programming.
Processors, especially those found on modern mobile devices, are erratic; the speed at which the loop is executed varies.
Why is this a problem? Let's say that updateGame() method moves a character right by 5 pixels. Now consider what would happen if updateGame() was not run at equal intervals. If the game slowed down and the loop took double the amount of time to execute again, the character would move at half speed. This would be disastrous for even a simple game like Temple Run.
So what a lot of game developers do is this. Instead of moving 5 pixels, the character would move 5 pixels MULTIPLED BY the amount of time that elapsed since the last execution of the loop (which we can define as deltaTime). This means that no matter how much the processor slows down, the character will always travel at the same speed.
Enough with the theory. Let's meet the first loop!
Lesson #1-15: The While Loop
We saw a quick example of a while loop above. Let's discuss it in a little more depth.
The while loop will continue to execute as long as the condition is satisfied.
Take a look at this example:
while (earthIsSpinning){
//The compiler will read this as:
//earthIsSpinning == true
System.out.println("The earth is still spinning.")
}
If this was an actual program, it would just flood your console as fast as the computer is capable of with the sentence "The earth is still spinning." At least for the predictable future.
We rarely want programs that run forever (unless you are running the Matrix).
So how do you end a while loop?
Simple. When the loop is executed to your satisfaction, you change the variable earthIsSpinning to false so that the condition is no longer satisfied. Then the loop will terminate.
A full class example follows:
We rarely want programs that run forever (unless you are running the Matrix).
So how do you end a while loop?
Simple. When the loop is executed to your satisfaction, you change the variable earthIsSpinning to false so that the condition is no longer satisfied. Then the loop will terminate.
A full class example follows:
public class Looping {
public static void main(String[] args) {
boolean earthIsSpinning = true;
int counter = 0;
while (earthIsSpinning) {
System.out.println("The earth is still spinning.");
System.out.println(counter);
counter++;
if (counter >= 10) {
earthIsSpinning = false;
} // ends If
} // ends While
} // ends Main
} // ends Looping Class
Most of this code is self explanatory, because it incorporates elements that we have seen before.
Let's talk about some of the things that you may have forgotten or have unanswered questions about.
Within the main class:
1. We create a boolean earthIsSpinning, and initialize the value to be true.
2. We also create a counter and set the value as 0;
A while loop that has the condition (earthIsSpinning == true) is created.
Inside it,
1. We display "The earth is still spinning."
2. We display the value of the integer counter.
3. We add 1 to counter's value.
An if statement is contained inside the while loop.
If counter is less than 10, this if statement is ignored!
With each iteration, or execution, of the while loop, the value of the counter integer, which begins at 0, increases by 1.
This means that after the 10th display, earthIsSpinning would be set equal to false, and the condition of the while loop will no longer be satisfied, meaning that it will terminate.
Why does this if statement have to be inside the while loop? Because if we put the if statement outside the while loop, it will only run once right after the first execution of the while loop, when counter is equal to 1. The if condition will not be satisfied and the statement will never be called again.
Another way you could end the loop is by calling break; whenever you need to. That way, you don't have to stop spinning the earth to stop your loop.
_____________________
Do you ever find it difficult to count? Me neither, but let's create a counting program for the heck of it.
This program will use two values: an initial value and a final value. It will then sequentially count the integers between the two values.
_____________________
Let's talk about some of the things that you may have forgotten or have unanswered questions about.
Within the main class:
1. We create a boolean earthIsSpinning, and initialize the value to be true.
2. We also create a counter and set the value as 0;
A while loop that has the condition (earthIsSpinning == true) is created.
Inside it,
1. We display "The earth is still spinning."
2. We display the value of the integer counter.
3. We add 1 to counter's value.
An if statement is contained inside the while loop.
If counter is less than 10, this if statement is ignored!
With each iteration, or execution, of the while loop, the value of the counter integer, which begins at 0, increases by 1.
This means that after the 10th display, earthIsSpinning would be set equal to false, and the condition of the while loop will no longer be satisfied, meaning that it will terminate.
Why does this if statement have to be inside the while loop? Because if we put the if statement outside the while loop, it will only run once right after the first execution of the while loop, when counter is equal to 1. The if condition will not be satisfied and the statement will never be called again.
Another way you could end the loop is by calling break; whenever you need to. That way, you don't have to stop spinning the earth to stop your loop.
_____________________
Do you ever find it difficult to count? Me neither, but let's create a counting program for the heck of it.
This program will use two values: an initial value and a final value. It will then sequentially count the integers between the two values.
_____________________
Figure 4: Looping Class
public class Looping {
public static void main(String[] args) {
int initialValue = 0;
int finalValue = 10;
int counter = 0;
if (initialValue < finalValue) {
System.out.println("Input accepted!");
System.out.println("Initial Value: " + initialValue);
System.out.println("Final Value: " + finalValue);
System.out.println();
System.out.println("Initiating count.");
System.out.println();
System.out.println(initialValue);
counter++;
while (initialValue < finalValue) {
initialValue++;
System.out.println(initialValue);
counter++;
}
if (initialValue == finalValue) {
System.out.println();
System.out.println("Counting complete.");
System.out.println("There are " + counter
+ " numbers (inclusive) between "
+ (initialValue - counter + 1) + " and " + finalValue
+ ".");
}
} else {
// Executed if: if (initialValue < finalValue) above is not true.
System.out.println("Final value is less than initial value!");
System.out.println("Please choose new values.");
}
}
}
The Output:
Try to study this code and see if you can figure out what it is doing.
It looks complex, but it is very straightforward!
We will analyze this in detail tomorrow!
_____________________
If you want to thank me for the guide, you can press Thanks or donate here or download TUMBL +!
It looks complex, but it is very straightforward!
We will analyze this in detail tomorrow!
_____________________
If you want to thank me for the guide, you can press Thanks or donate here or download TUMBL +!