The Coder's Handbook

Loops

FOR LOOPS

Syntax


A for loop follow this syntax:


for(initialization; termination; increment)

{

statement(s)

}


Consider an example that runs 5 times. Each time the loop runs is called one iteration of the loop.


for(int i = 0; i < 5; i++)

{

System.out.print(“*”);

}


*****


In the example above, the for loop consists of three parts:

  • Initializing a loop variable i starts at 0

  • Setting a condition for the loop to continue goes while i < 5

  • Incrementing the loop variable i goes up by 1 each time


Note: Programmers often use the letter “i” for loops, but this is just a convention. Unlike your other variables (which should have clear, descriptive names) a loop variable should only be a single letter. This is because they’re so common, and only exist for a short time, that it rarely becomes confusing.




Nested Loops


When you put one loop inside another loop, it is a nested loop. Keep in mind that you can't use the same loop variable, since they share scope.


for(int i = 0; i < 3; i++)

{

for(int j = 0; j < 5; j++)

{

System.out.print(“*”);

}

System.out.println();

}


*****

*****

*****


Notice that in this example we're printing 3 times 5 --> 15 stars total.


WHILE LOOPS

Syntax


A while loop follows the following format:


while(expression)

{

statement(s)

}


Let’s start by considering a few examples of while loops. These examples reference made-up methods and variables; you can imagine what they might represent from their names.


while(!isWinner())

{

playerTurn();

cpuTurn();

}


while(num > 0)

{

num = num/2;

count++;

}


A while loop works just like an if statement, except the code inside of it will repeat until the condition is no longer true.


One common mistake is that there is no such thing as a “while / else.” If you want to have a second while loop happen, simply place it after the first one and set appropriate conditions.


Do While Loops


A do-while loop follows the following format:


do

{

statement(s)

} while(expression);


A do while loop works exactly like a while loop, except…

  • It will always execute at least one time

  • It is bottom-checking, meaning it will check the expression after each iteration of the loop



BRANCHING STATEMENTS

Syntax


  • The break statement can be used to exit out of a loop early

  • The continue statement can be used to start the next iteration of a loop

  • A return statement can be used to exit the entire method containing the loop.

RESOURCES