[Android Software Development] tjdwowh:
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.

Games, despite popular belief, 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.

[COLOR="DarkRed"]while (playerAlive == true){[/COLOR]

updateGame(deltaTime);
renderGame(deltaTime);

[COLOR="DarkRed"]}[/COLOR]

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 introductions. 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:

[COLOR="DarkRed"]while (earthIsSpinning){[/COLOR]
//Remember that when you have a boolean without '== true' or '== false', the former is understood.
//The compiler will read this as:
//earthIsSpinning == true

System.out.println("The earth is still spinning.")

[COLOR="DarkRed"]}[/COLOR]

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. 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:

[COLOR="Blue"]public class Looping {
[/COLOR]	[COLOR="RoyalBlue"]public static void main(String[] args) {[/COLOR]

boolean earthIsSpinning = true;
int counter = 0;

[COLOR="MediumTurquoise"]while (earthIsSpinning){[/COLOR]
System.out.println("The earth is still spinning.");
System.out.println(counter);
counter++;

[COLOR="Teal"]if (counter >= 10){[/COLOR]
earthIsSpinning = false;
[COLOR="Teal"]}[/COLOR]

[COLOR="MediumTurquoise"]}[/COLOR]

[COLOR="RoyalBlue"]}[/COLOR]
[COLOR="Blue"]}[/COLOR]

And this is the output:

The earth is still spinning.
0
The earth is still spinning.
1
The earth is still spinning.
2
The earth is still spinning.
3
The earth is still spinning.
4
The earth is still spinning.
5
The earth is still spinning.
6
The earth is still spinning.
7
The earth is still spinning.
8
The earth is still spinning.
9

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.

_____________________

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.

_____________________

[COLOR="Blue"]public class Looping {
[/COLOR]	[COLOR="RoyalBlue"]public static void main(String[] args){[/COLOR]

int initialValue = 0;
int finalValue = 10;

int counter = 0;

[COLOR="DarkRed"]	if (initialValue < finalValue) {[/COLOR]
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++;

[COLOR="DarkOrange"]while (initialValue < finalValue) {[/COLOR]
initialValue++;
System.out.println(initialValue);
counter++;

[COLOR="DarkOrange"]}[/COLOR]

[COLOR="Olive"]if (initialValue == finalValue){[/COLOR]
System.out.println();
System.out.println("Counting complete.");
System.out.println("There are " + counter + " numbers (inclusive) between " + (initialValue - counter + 1) + " and " + finalValue + ".");
[COLOR="Olive"]	}[/COLOR]

[COLOR="DarkRed"]	} else {[/COLOR]
[COLOR="SeaGreen"] //Executed if: if (initialValue < finalValue) above is not true.[/COLOR]

System.out.println("Final value is less than initial value!");
System.out.println("Please choose new values.");
[COLOR="Red"]}
[/COLOR]
[COLOR="RoyalBlue"]}[/COLOR]
[COLOR="Blue"]}
[/COLOR]

The Output:

Input accepted!
Initial Value: 0
Final Value: 10

Initiating count.

0
1
2
3
4
5
6
7
8
9
10

Counting complete.
There are 11 numbers (inclusive) between 0 and 10.

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 +!

Thank you guys for reading and I'm here if you have any questions!

PM me or email me!