Java Chap7 Iteration through Loops ( Prof. Ananda M Ghosh)

20
Chapter 7: Iterations through Loops 7.0 Introduction Iteration means repetition or looping over a portion of a program. For solving problems by a computer, it becomes very often necessary to loop over a portion of a program, again and again, so that a desired goal is achieved. For example, marks sheets for 30 students of a class are to be prepared by taking help of a computer program. A marks sheet preparing procedure for every student will be the same but that procedure is got to be repeated 30 times to complete the total job. Thus the marks-sheet processing portion is got to be repeated as many times as there are number of students. For the marks-sheets case, the repetition will be carried out for a known number (equal to the number of students) of times. The for loop is generally used when it is known in advance how many times a loop is got to be executed. 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.

description

Looping in Java language, for Loop, nested loops, while-do loops, do-while loop, brake in a loop,

Transcript of Java Chap7 Iteration through Loops ( Prof. Ananda M Ghosh)

Page 1: Java Chap7 Iteration through Loops ( Prof. Ananda M Ghosh)

Chapter 7:

Iterations through Loops

7.0 Introduction

Iteration means repetition or looping over a portion of a program. For solving problems by a computer, it becomes very often necessary to loop over a portion of a program, again and again, so that a desired goal is achieved. For example, marks sheets for 30 students of a class are to be prepared by taking help of a computer program. A marks sheet preparing procedure for every student will be the same but that procedure is got to be repeated 30 times to complete the total job. Thus the marks-sheet processing portion is got to be repeated as many times as there are number of students. For the marks-sheets case, the repetition will be carried out for a known number (equal to the number of students) of times. The for loop is generally used when it is known in advance how many times a loop is got to be executed.

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.

7.1 For Fixed Number of Iterations – for loop

The for loop iteration is used when number of repetition is fixed and known in advance. It has a general form of:

for ( initialization; condition test; iteration) {

// body of the loop

}

If only one statement is being repeated, the curly brackets may not be used.

For example,

Page 2: Java Chap7 Iteration through Loops ( Prof. Ananda M Ghosh)

for ( n = 0; n < 15; n++)System.out.println (“ repeat count number = ” + n);

Orfor ( 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 –

Example 7.1 Demo of a for loop Statement

public class ForDemo{public static void main() { double a, value; int n;

// multi-statement for loop for ( a = -3; a <= 3; a = a + .5) { value = a*a + 2* a - 4; System.out.println( " result will be " + value + " for a = " + a);

}

// single statement for loopfor ( n=0; n < 10; n++)System.out.println (" count number is = " + n);

} // main ends here} // class ends here

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.

Page 3: Java Chap7 Iteration through Loops ( Prof. Ananda M Ghosh)

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

}

Time delay loop can easily be created in the following fashion:-

for( int t=0; t < 600; t++);// having an empty loop body

7.1.2 Multiple Initialization and Iteration Expressions in a for Loop

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.

Example 7.2 Demo of Multi-Statement for

public class MultiStatmntFor{

public static void main() { int x, y; for ( x = 0, y =10; x < y; x +=2, y -=2) { System.out.println (" x = " + x + " y = " + y); System.out.println (" Values of x & y in next iteration"); }

Page 4: Java Chap7 Iteration through Loops ( Prof. Ananda M Ghosh)

System.out.println (" x = " + x + " y = " + y); System.out.println (" Loop ends as x exceeds y"); } }

If you run this program, you will see the output as –

x = 0 y = 10Values of x & y in next iterationx = 2 y = 8Values of x & y in next iterationx = 4 y = 6Values of x & y in next iterationx = 6 y = 4Loop 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.

7.1.3 Nested for Loops

Java allows a loop to be nested that is one loop may enclose one or more loops inside it.

Example 7.3 Demo of Nested for Loops

public class NestedFor{

public static void main() { int i,j; for( i=5; i >= 0; i--) { for ( j=i; j < 5; j++) // nesting System.out.print ("@"); // inner loop statement System.out.println (); // outer loop statement } } }

After compiling and executing this program, you will see the output as –

@@@@@@@@@@@@@@@

Page 5: Java Chap7 Iteration through Loops ( Prof. Ananda M Ghosh)

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.

7.2 Unknown Number of Iterations –

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.

7.2.1 while loop

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.

Example 7.4 Demo of While-do Statement

public class WhileDemo{

public static void main() { int n = 100; while ( n > 0) { System.out.println (" Count down : " + n); n -=10; } } }

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;

Page 6: Java Chap7 Iteration through Loops ( Prof. Ananda M Ghosh)

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 –

Example 7.5 Demo of Null body while

public class NullBodyWhile{

// to determine the midvalue of a range public static void main(){

int low = 20, high = 50; while (++low < --high); // null body System.out.println (" Midvalue is = " + low); System.out.println (" Present value of high = " + high); }

}

You will get the following output when you run this program –

Midvalue is = 35Present 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.

7.2.2 do-while loop

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

Page 7: Java Chap7 Iteration through Loops ( Prof. Ananda M Ghosh)

expression. As a result the loop body gets executed at least once even if the condition is checked to be false.

The general form of the do-while loop is –

do { // loop body

} while ( condition);

The condition must be a Boolean expression, which can return either true of false. Here is an example.

Example 7.6 Demo of do-while Statement

public class DoWhileDemo { public static void main() { int n = 5; System.out.println (" First go of the loop"); do { System.out.println (" Looping after condition ckeck"); n--; } while ( n >0); System.out.println (" After coming out of the loop"); } }The execution of this program will give the output ---

First go of the loopLooping after condition checkLooping after condition checkLooping after condition checkLooping after condition checkLooping after condition checkAfter coming out of the loop

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 –

Example 7.7 Demo of a Menu Selection Program

public class MenuDemo{

public static void main() throws java.io.IOException { char select;

Page 8: Java Chap7 Iteration through Loops ( Prof. Ananda M Ghosh)

System.out.println (" Menu Choice:"); System.out.println (" 1 -- for"); System.out.println (" 2 -- while-do"); System.out.println (" 3 -- do-while"); System.out.println (" Choose any one"); do { select = (char) System.in.read(); } while ( select < '1' || select > '3'); 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:

1) How to read a char from a keyboard using System.in.read() method.

2) Discussions about the importance of IOException will be made in chapter-11.

3) How to put a selection Menu on a VDU screen.

4) How to combine switch control with a do-while statement.

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

Page 9: Java Chap7 Iteration through Loops ( Prof. Ananda M Ghosh)

Picture 7.1

7.3 Uses of continue & break

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.

Example 7.8 Use of brake in Loop Statements

public class BreakDemo{

public static void main() { for ( int n = 1; n <50 ; n++) { if ( n = = 8) break; System.out.println (" Present value of n is = "+ n); } System.out.println (" The for-Loop terminates due to break."); int j=3; while ( j < 30) { if (j = = 10) break; System.out.println (" Current value of j is: "+ j); j++; } System.out.println (" Brake terminates the while-Loop."); } } After execution of this program, you will see the output as –

Present value of n is = 1

Page 10: Java Chap7 Iteration through Loops ( Prof. Ananda M Ghosh)

Present value of n is = 2Present value of n is = 3Present value of n is = 4Present value of n is = 5Present value of n is = 6Present value of n is = 7The for-Loop terminates due to break.Current value of j = 3Current value of j = 4Current value of j = 5Current value of j = 6 Current value of j = 7Current value of j = 8Current value of j = 9Break terminates the while-Loop.

7.3.1 Break with a Label as a Special form of GoTo

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 –

// Example 7.9 Demo of Labeled break

public class LabelBreak{public static void main () {

System.out.println (" This is an example of Labeled Break.");

newstart : for ( int i =0; i < 3; i++) { // Label name newstart System.out.println (" Outer Loop Count = " + i); for (int n = 1; n < 60 ; n++ ) { if ( n = = 6) break newstart; System.out.println (" Inner loop count = " + n); } System.out.println (" The end of outer-loop.");

Page 11: Java Chap7 Iteration through Loops ( Prof. Ananda M Ghosh)

} System.out.println (" Control comes out of both the Loops"); }

}

If you run this program, you will see the output as shown below –

This is an example of Labeled Break.Outer Loop Count = 0

Inner Loop Count = 1Inner Loop Count = 2Inner Loop Count = 3Inner Loop Count = 4Inner Loop Count = 5Control comes out of both the Loops.

We have seen how to use break and labeled break statements. Now we will discuss about the use of the continue statement.

7.3.2 Continue Statement

For fulfillment of some programming requirements, it may be necessary to skip a portion of the loop body in a particular iteration and to continue looping with the next iteration. In a for-loop, control goes first to the iteration portion and then to the condition. In while-do and do-while loops, the continue statement transfers control directly to the conditional expression. Let us now see a few examples with the use of continue statements.

Example 7.10 Using Continue

public class ContinueDemo{public static void main() {

for ( int i =1; i < 50; i++) { if ( i % 3 != 1) continue; System.out.print ( i + " "); } }

}

I f you run this program, you will see the output as –

1 4 7 10 13 16 19 22 25 28 31 34 37 40 43 46 49

Page 12: Java Chap7 Iteration through Loops ( Prof. Ananda M Ghosh)

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.

7.4 More about Nested Loops

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.

/* Example 7.11 Use of both Continue & Break Statements */

public class ContinueBreak{

public static void main() { int i,j, k; outer: for ( i =1; i < 10; i++) { // Label name outer System.out.println (" Pass: " + i); for (k = 2; k < 6; k++) { for ( j = 1; j < 20; j++){ 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.

Let us now see an example of labeled continue.

Page 13: Java Chap7 Iteration through Loops ( Prof. Ananda M Ghosh)

Example 7.12 Demo of Labeled Continue

public class LabeledContDemo{public static void main() {

again: for (int j=1; j < 10; j ++) { // Label name again for (int k = 1; k< 10; k++) { if (k > j) { System.out.println (); continue again; } System.out.print (" " + j); } } }

} By running this program you will see the output as –

11 22 3 33 4 4 44 5 5 5 55 6 6 6 6 66 7 7 7 7 7 77 8 8 8 8 8 8 88 9 9 9 9 9 9 9 9

7.5 Converting one loop form into another loop form

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.

Example 7.13 Loop Form Conversion Demo

public class ConvertDemo {

public static void main() { int i; for ( i= 1; i < 10; i++) System.out.print (i + " "); System.out.println (" for-loop complete.");

Page 14: Java Chap7 Iteration through Loops ( Prof. Ananda M Ghosh)

// converted into while-do

i = 1; while ( i < 10) { System.out.print( i + " "); i++; } System.out.println (" while-do loop complete.");

// converted into do-while loop

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

In solving iterative problems, looping technique is often used. We have discussed about three looping statements, namely for-loop, do-while and while-do loops. The for-loop is preferred for known number iterations, whereas do-while and while-do are preferred for unknown number of iterations. However, one loop form can be converted into another form quite easily.

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.