Java Chap7 Iteration Through Loops (Prof. Ananda M Ghosh)
Java Chap7 Iteration Through Loops (Prof. Ananda M Ghosh)
7.0 Introduction
There are some kinds of problems where the number of iterations that will be
required to reach the final goal may not be known in advance. In such cases, number of
iterations can be controlled by taking help of some condition expression and using while or
do-while statements. The condition expression determines how many times the looping
will be carried out. For example, suppose you set a condition like (allowed error <= 0.5) to
terminate a do-while loop. How many iterations will be required to reach that state (i.e. error
<= 0.5) is not known to the programmer, but the looping required to keep error within the
target, will automatically be controlled by the condition expression. Infinite looping may
occur due to improper setting of the condition expression. We will see how a java
programmer can also tackle such exceptional conditions.
The for loop iteration is used when number of repetition is fixed and known in advance. It
has a general form of:
If only one statement is being repeated, the curly brackets may not be used.
For example,
for ( n = 0; n < 15; n++)
System.out.println (“ repeat count number = ” + n);
Or
for ( a = -3; a <= 3; a = a + .5) {
value = a*a + 2* a – 4;
System.out.println (“result will be “ + value + “ for a = “ + a);
}
Let us now see a program where both the types of for loop statements have been used –
Just enter this program, compile and execute to see what output appears on the terminal
window. Try to interpret the outputs you obtain.
Loop variables used in the above program are a and n, both of which have been
declared outside the loop statement but not used anywhere else. In such cases, variables
that control for loops can easily be declared inside the initialization portion. That is,
for ( double a = -3; a <= 3; a = a +.5) could be used in the first for and
for ( int n =0; n < 10; n++) could also be used for the second for.
The scope of inside variables ends when the for statements end. Outside that for loop,
the variables will cease to exist can be used for some other purpose.
7.1.1 for loop – Some Variations
The three sections of a for loop (namely, initialization, condition test, iteration) can be
used for many other purposes. Either the initialization or the iteration expression or both may
be kept blank. Even all three sections of a for loop can be kept blank creating an infinite
loop. For example –
int i = 0;
for ( ; i < 10, i++) { // first section absent
// loop body for fixed number iterations
}
int i =0;
for ( ; !done; ) {
// first and third sections absent
// loop body repeats until test condition not fulfilled
}
for ( ; ; ) {
// loop body
// for infinite iterations
// all three sections absent
}
It is possible to use more than one statements in the initialization and iteration portions of
a for loop. Now see an example of such a usage.
x = 0 y = 10
Values of x & y in next iteration
x=2 y=8
Values of x & y in next iteration
x=4 y=6
Values of x & y in next iteration
x=6y=4
Loop ends as x exceeds y
Two variables x & y control the loop, in this example and they remain included in
the same for statement. Each statement in initialization and iteration portions is separated
by comma but as portion delimiter -- ; is used as usual.
Java allows a loop to be nested that is one loop may enclose one or more loops inside it.
After compiling and executing this program, you will see the output as –
@
@@
@@@
@@@@
@@@@@
In this example, the j-loop is nested inside the i-loop. As j-loop has only one statement,
no {..} has been used. Whereas i-loop has used { ..} because it has more than one
statements.
As mentioned earlier, for unknown number of iterations while or do-while statements are
used. Both are looping statements and execute the same set of instructions until a
terminating condition gets satisfied. We will now examine them one by one.
While loop repeats a statement or a group of statements present in a block while its
controlling expression is true. It has a general form:--
while ( condition) {
// loop body
The condition should be a boolean expression. The body of the loop will go on looping as
long as the condition remains true.
Just examine what output you obtain after running this program.
Since the while loop tests the condition first, the body of the loop may not be executed
even once if the condition does not get satisfied. Take an example --
|
|
int x = 15, y = 20;
while ( x > y) {
Body of the loop
}
|
|
Here the body of the loop will never be executed because x remains less than y
always.
The body of a while loop can even be empty. In that case the body part will be absent and
the while statement will look like ---
while ( condition);
The question is, can there be any use of such null body while loop statement? Here is an
example –
You will get the following output when you run this program –
Midvalue is = 35
Present value of high = 35
The nulls body while loop worked in this way. Look at the condition expression
where “low” was continuously incremented and “high” decremented until the low value
reached the mid-value. At the next cycle, “low” became higher than “high” and the loop
terminated then and there. The program control then goes to the next statement and the
results get printed.
Sometimes it becomes desirable to execute the body of the while loop at least
once. In that case the condition expression is placed at the end of the loop body rather than
at the beginning. The do-while loop executes its body first and then checks the condition
expression. As a result the loop body gets executed at least once even if the condition is
checked to be false.
do {
// loop body
} while ( condition);
The condition must be a Boolean expression, which can return either true of false. Here is an
example.
The do-while loop becomes very much useful when you like to process a menu selection
because the menu’s choices must be displayed first and then processing will be carried out
as per selection. Here you study an example –
switch (select) {
case '1' :
System.out.println (" for: is used for known number of Iterations.");
System.out.println (" for: has three portions.");
System.out.println (" (initialization, condition, iteration)");
break;
case '2' :
System.out.println (" while-do: is used when condition is checked first.");
System.out.println (" while-do: body may not be executed at all.");
System.out.println (" while-do: may have a null body.");
break;
case '3' :
System.out.println (" do-while: is used when body is to be executed at least
once.");
System.out.println (" do-while: with switch can make menu selection.");
break;
}
}
}
The program of example -7.7 demonstrates the following important points worth noting:
To understand the beauty of a menu controlled programs, enter, compile and execute the
program and observe the output with the choice 2 (Picture 7.1).
Picture 7.1
Continue and break can control a program execution sequence like a jump statement as used
in conventional languages. The break is used to exit a loop. Break can be used to exit any
type of loop statements – for, while-do or do-while. Even break can cause an exit from an
infinite loop. Let us first examine a few examples on break statements.
Present value of n is = 1
Present value of n is = 2
Present value of n is = 3
Present value of n is = 4
Present value of n is = 5
Present value of n is = 6
Present value of n is = 7
The for-Loop terminates due to break.
Current value of j = 3
Current value of j = 4
Current value of j = 5
Current value of j = 6
Current value of j = 7
Current value of j = 8
Current value of j = 9
Break terminates the while-Loop.
Java does not support goto statement as like many conventional languages. The
goto violates structured programming concept, therefore, good programmers always try to
avoid that statement even in conventional programming. In some situations, like exception
handling or breaking a deeply nested loops, goto like statement may be helpful. To
deal with such situations, java provides brake statement with a label. The general form of
a Labeled break statement is:-
break <label>;
where label identifies a block of codes. When such a statement is encountered the program
flow-control jumps out to the block marked with that particular label. Here is an example –
}
}
If you run this program, you will see the output as shown below –
We have seen how to use break and labeled break statements. Now we will discuss about
the use of the continue statement.
1 4 7 10 13 16 19 22 25 28 31 34 37 40 43 46 49
Observe that the difference between consecutive numbers is 3 – Why? Just see how
easily you can generate an AP series using such a small java program.
Like brake statement, continue statement also may use label to indicate from
which new point to start continue. We will see that in the next section.
We have already discussed about the nested loop in sec- 7.1.3. Through examples
-7.8 and 7.9 we have seen how nested loops can be terminated using break statements.
Now we will see how nested loops can be controlled using both continue & break
statements.
if ( j % k != 1) continue;
System.out.print (j + " ");
}
System.out.println ();
}
if ( i = = 3 ) break outer;
System.out.println ();
}
}
}
Just examine what output do you obtain by running this program. But carefully note
about one thing that j-loop is nested into k-loop, which is again nested by i-loop, that is,
nesting is three levels deep.
1
1 2
2 3 3
3 4 4 4
4 5 5 5 5
5 6 6 6 6 6
6 7 7 7 7 7 7
7 8 8 8 8 8 8 8
8 9 9 9 9 9 9 9 9
Although it has been stated earlier that for-loop is preferred for fixed number of
iterations, which does not mean that a for-loop cannot be converted into a do-while or
while-do types of loop. Loop form conversion is now demonstrated by an example.
i = 1;
while ( i < 10) {
System.out.print( i + " ");
i++;
}
System.out.println (" while-do loop complete.");
i = 1;
do {
System.out.print( i + " ");
i++;
} while ( i < 10);
System.out.println (" do-while loop complete.");
System.out.println (" All 3 loops produce the same results.");
}
}
By running this program you will see the output as shown below –
1 2 3 4 5 6 7 8 9 for-loop complete.
1 2 3 4 5 6 7 8 9 while-do loop complete.
1 2 3 4 5 6 7 8 9 do-while loop complete.
Thus it is proved that any loop form can be converted into another loop form to have
the same result but it may be convenient to write for-loop for known number of iterations
and do-while (with at least one loop-body execution) and while-do (allowing even null loop-
body execution) for unknown number of iterations.
7.6 Conclusions
Use of break and continue statements are often used to control looping operations,
especially in nested loops. We have explained that by taking help of a good number of
examples. The importance of nested loops has also been made clear. Looping also helps
problem solving by trial-and error.