

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!


Announcements: Reminder: Quiz on Monday, Nov 7. Nested for loops A for loop can contain any other statements, including for loops - these are called nested for loops. [Open the for-loops project โ students can follow along] Let's try to figure out what happens with this code segment (in method firstExample): 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. [Write this code in front of the students โ get them to help by asking questions. There is an empty method in the Example class for you to fill in. You should end up with something similar to: for ( int i = 0; i <= 12; i++ ) { for ( int j = 0; j <= 12; j++ ) { System.out.print( i * j + " " ); } System.out.println(); } The output 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, ... ); Format strings: %[width]d - integer values %[width][.precision]f - floating point values width โ number of characters to be formatted precision โ number of digits after the decimal point %7.2f 7 character wide field, 2 digits after decimal point So, let's figure out how to make our program print out the table nicely. More Nested For Loops We can use the loop control variable of the outer loop to control the number of times that the inner loop iterates. Let's try to figure out what this loop does (example2 method): for ( int i = 0; i < 4; i++ ) { for ( int j = 0; j <= i; j++ ) { System.out.print(""); } System.out.println(); } Possible approaches โ step though the code on the board, showing the values of i, j, and the printout. Or use the BlueJ debugger. And another one... (example3 method): for ( int i = 0; i < 4; i++ ) { for ( int j = i; j < 4; j++ ) { System.out.print(""); } System.out.println(); }