

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 started looking at nested for loops. Let's say we wanted a nested for loop to print: 12345 12345 12345 [Use presenter to ask questions: What would the outer loop look like? What would the inner loop look like?] OK, How about nest for loops to produce this? 1 12 123 1234 How about a program that prints a multiplication table from 1 to 12 [draw it on board] What does outer loop look like? What is the inner loop? So, let's do this in BlueJ - [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 Let's do one more triangle that is a bit more complicated - Try to write method that prints triangles like this:
Lab Complete your loops lab from last class.