

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


Last time we looked at the for statement for ( ForInit; ForExpression; ForUpdate ) Statement Draw flowchart, using above labels. Then redraw using below example. int value = 1; for ( int i = 0; i < 5; i++ ) { System.out.println( value ); value *= 2; } Remember, loop control variable does not have to increase, and it does not have to change its value by 1. for ( int count = 20; count > 0; count -= 7 ) { System.out.println( count ); } We also saw that a for loop can be converted to a while loop, but the for loop is typically used when we know ahead of time how many iterations there are going to be. Do While There is a second form of the while loop - in this form, the boolean expression is at the end. do statement; while ( <boolean-expr> ) Draw flowchart. In this form of the while loop, the statement is always executed at least once. Compare with other form of flow chart. One use for this form might be user input validation: int value; do { System.out.print("Please enter a positive number: "); value = stdin.nextInt(); } while ( value <= 0 )
Compare with the code that uses standard while loop: int value; System.out.print( "Please enter a positive number: "); value = stdin.nextInt(); while ( value <= 0 ) { System.out.print("Please enter a positive number: "); value = stdin.nextInt(); } Discuss importance of UI validation. Note that you can use do-while when action must occur at least once. While is used when action may occur 0 times. Note that the while format is much more common. Nested for loops A for loop can contain any other statements, including for loops - these are called nested for loops. Let's try to figure out what happens with this code segment: for ( int i = 0; i < 2; i++ ) { for ( int j = 0; j < 3; j++ ) { System.out.println( "i is " + i + ", j is " + j ); } } Identify outer loop Identify inner loop How many times does the outer loop execute How many times does the inner loop execute for each iteration of the outer loop? How many times does the inner loop execute all together? So, nested for loop gives a multiplicative effect. Let's try to write a program that prints out a multiplication table, up to 12 * 12. The format isn't very nice, is it? Java has another printing method that allows us to format our output. The syntax is kind of bizarre - it originated in the C language many years ago. System.out.printf( String formatString, variable1, variable2, ... );