We have now seen how to iterate by using recursion; recursion is a powerful tool, but Java also supports loops for iteration. A loop lets you go back and execute the same code over and over again depending on a condition.
When talkin about loops we have: * the loop condition which determines whether the loops keeps executing * the body of the loop, which is the statements we want to execute several times (it is good practice to put the body between braces, even if it is just one statement)
1. The do-while loop
The do-while loop allows you to execute a block of statements while a condition is true (your statements inside the loop should change the condition so that it eventually isn’t true, or you get into an infinite loop). The statements are executed at least once. before checking the condition.
It’s syntax is as follows:
do {
// body of the loop
} while(condition) ;
Notice that the semicolon at the end is part of the syntax and needed.
For example, we could write a function that reads numbers from the keyboard, until it reads a 0, and returns its sum. The function would be:
public static int readAndSum(PrintStream out, Scanner in)
{
int sum=0;
int input;
do {
out.println("Please enter a number (0 to stop)");
input=in.nextInt();
sum+=input;
} while(input!=0);
return sum;
}
The do-while loop is not commonly used (most people use while or for loops, shown below), but can be useful when we always want to execute the body of the loop at least once.
2. The while loop
The while loop puts the condition at the top, and so it checks whether it is true before doing the body of the loop; if the condition is not initially true, it never gets executed at all.
The syntax for the while loop is as follows: It’s syntax is as follows:
while(condition){
// body of the loop
}
notice that, unlike the do-while loop, we do not need a semicolon at the end.
A common trick, if we want the body to run at least once, is to either copy the body of the loop or to set up the condition so it is initially true.
For example, the following function would read numbers until 0 (as in the do-while example) and return their sum, but using a while loop.
public static int readAndSumWhile(PrintStream out, Scanner in)
{
int sum=0;
int input;
out.println("Please enter a number (0 to stop)");
input=in.nextInt();
sum=sum+input;
while(input!=0) {
out.println("Please enter another number (0 to stop)");
input=in.nextInt();
sum+=input;
}
return sum;
}
2.1. counting with while loops
Many times we need to go through a range of numbers; basically to count, and so something with the numbers as we count; we can count with a while loop by creating a variable that will sequentially take all the values we need, compare the variable with our upper bound, and increment it inside the loop (usually after doing whatever we were doing).
So, for example, a function
static void countAndPrintWhile(int low, int high, PrintStream out) {
int i=low;
while(i<=to) {
out.println(i);
++i;
}
}
And we can raise a base to a certain power by counting all numbers from 1 to the desired power, and multiplying by the original number each time; as follows:
int power(int base, int exponent)
{
int pow=1;
int counter=0;
while(counter<exponent) {
pow*=base;
++counter;
}
return pow;
}
Notice we could be counting down (and we would decrement our variable), or do something different, like adding 2 (to get all even numbers) each time. Incrementing and counting up are the most common, though.
static void countDownWhile(int high, int low, PrintStream out) {
int i=high;
while(i>=low) {
out.println(i);
--i;
}
}
3. for loop
This counting pattern is so common that Java (borrowing from C) has a special loop for this, the for loop.
The for loop is basically a while loop, but with the initialization, condition and increment written in the same line.
Its syntax is:
for(initialization; condition; increment){
// body of the loop
}
For example, we can count up with a for loop as follows:
static void countAndPrint(int from, int to, PrintStream out) {
for(int i=from; i<=to; ++i) {
out.println(i);
}
}
And we can raise a number to a given power as follows:
int power_for(int base, int exponent)
{
int pow;
for( pow=1; exponent>0; --exponent) {
pow*=base;
}
return pow;
}
The for loop is basically equivalent to the while loop; the only difference is that, if you declare a variable in the initialization clause, its scope is only within the loop, not outside of it.
Notice that all 3 parts of the loop, initialization, condition and increment are optional; you just need to put the corresponding ; and leave it blank (we will see some examples later).
4. break and continue
Initially, loops were promoted as having only one way to get out of it (see [1]). Although this is a good idea, we sometimes want to exit in the middle of a loop. The keywords break and continue let us modify the execution of a loop.
4.1. break
When you are inside a loop, the keyword break gets you out of the loop immediately(you normally put it inside the loop). Execution continues right after the body of the loop. This allows you to get out in the middle of a loop; this can be convenient, but also confusing, so use with some caution.
For example, we could write a function that reads numbers until it gets -1 and return their sum, using a while statement with true as the condition (this would be an infinite loop without a break, as the condition never changes) and a break, as follows:
public static int readAndSumBreak(PrintStream out, Scanner in)
{
int sum=0;
int input;
while( true ) {
out.println("Please enter a number (-1 to stop)");
input=in.nextInt();
if(input==-1)
break;
sum+=input;
}
return sum;
}
As an interesting aside, we mentioned in a for loop all parts (initialization, condition and increment) are optional; in particular, if we make all empty, we get an equivalent of while(true), as in the following example:
public static int readAndSumBreak(PrintStream out, Scanner in)
{
int sum=0;
int input;
for( ; ; ) {
out.println("Please enter a number (-1 to stop)");
input=in.nextInt();
if(input==-1)
break;
sum+=input;
}
return sum;
}
4.2. continue
The keyword continue lets us skip the rest of the body of a loop (from when it is executed until the end of the body). The execution continues with the checking of the condition.
For example, the following function uses continue to ensure only even numbers are added to the sum.
---
public static int readAndSumEven(PrintStream out, Scanner in)
{
int sum=0;
int input;
while( true ) {
out.println("Please enter a number (-1 to stop)");
input=in.nextInt();
if(input == -1) {
break;
}
if(!isEven(input)) {
continue;
}
sum += input;
}
return sum;
}
---
5. More examples
6. Summary
-
Loops allow you to execute code a bunch of times, while a condition is true.
-
Loops have a condition and a body. The loop will execute the body while the condition is true.
-
The do-while syntax is as follows:
do {
// body of the loop
} while(condition) ;
-
The
whilesyntax is as follows:
while(condition){
// body of the loop
}
-
the
forloop is like a while loop, with the initialization, condition and increment in the same line; its syntax is as follows (the semicolons are part of the syntax), and each one of the parts is optional
for(initialization; condition; increment){
// body of the loop
}
-
Inside a loop, the
breakkeyword will get you out of the loop -
Inside a loop, the
continuekeyword will skip the rest of the body of the loop (and send you to check the condition again). -
You normally guard any
breakandcontinueinside if statements, as a different way to get out of the loop.
7. Exercises
-
What would the following piece of code write ?
-
Given the