41
Nesting Loops Nesting Loops (That’s loops inside of (That’s loops inside of loops. loops. Why not?) Why not?)

Nesting Loops (That’s loops inside of loops. Why not?)

Embed Size (px)

Citation preview

Nesting LoopsNesting Loops

(That’s loops inside of loops.(That’s loops inside of loops.

Why not?)Why not?)

Consider a line of asterisks:Consider a line of asterisks:

*********************...*********************...

How can I do this in a program?How can I do this in a program?

row

column

Consider a line of asterisks:Consider a line of asterisks:*************…*************…

final int numberCols = 20;final int numberCols = 20;

for (int col=1; col<=numberCols; col+for (int col=1; col<=numberCols; col++) {+) {

System.out.print( "*" );System.out.print( "*" );

}}

System.out.println();System.out.println();

Say I want rows and rows of Say I want rows and rows of this line.this line.

**************…**************…

**************…**************…

**************…**************…

..

..

..

final int numberRows = 5;final int numberRows = 5;

final int numberCols = 20;final int numberCols = 20;

//output all of the lines//output all of the lines

for (int row=1; row<=numberRows; row++) for (int row=1; row<=numberRows; row++) {{

//output one line//output one line

for (int col=1; col<=numberCols; col++) {for (int col=1; col<=numberCols; col++) {

System.out.print( "*" );System.out.print( "*" );

}}

System.out.println();System.out.println();

}}

Say instead we want:Say instead we want:

* * * * …* * * * …

* * * * …* * * * …

..

..

..Note space between asterisks.

for (int row=1; row<=numberRows; row+for (int row=1; row<=numberRows; row++) {+) {

for (int col=1; col<=numberCols; col++) for (int col=1; col<=numberCols; col++) {{

System.out.print( "* " );System.out.print( "* " );

}}

System.out.println();System.out.println();

}}space

Say we want a Say we want a checkerboard:checkerboard:

for (int row=1; row<=numberRows; for (int row=1; row<=numberRows; row++) {row++) {

for (int col=1; col<=numberCols; for (int col=1; col<=numberCols; col++) {col++) {

System.out.print( "* " );System.out.print( "* " );

}}

System.out.println();System.out.println();

}}

for (int row=1; row<=numberRows; for (int row=1; row<=numberRows; row++) {row++) {

for (int col=1; col<=numberCols; for (int col=1; col<=numberCols; col++) {col++) {

System.out.print( "* " );System.out.print( "* " );

}}

System.out.println();System.out.println();

}}

Can mod (%) help us somehow?Can mod (%) help us somehow?

Say we want a Say we want a checkerboard:checkerboard:

final int width = 8;final int width = 8;

//output all of the rows//output all of the rows

for (int r=1; r<=width; r++) {for (int r=1; r<=width; r++) {

//output all of the columns within the row//output all of the columns within the row

for (int c=1; c<=width/2; c++) {for (int c=1; c<=width/2; c++) {

if ( (r%2) == 0 ) {if ( (r%2) == 0 ) {

System.out.print( " *" );System.out.print( " *" );

} else {} else {

System.out.print( "* " );System.out.print( "* " );

}}

}}

System.out.println();System.out.println();

}}

final int width = 8;final int width = 8;

//output all of the rows//output all of the rows

for (int r=1; r<=width; r++) {for (int r=1; r<=width; r++) {

//output all of the columns within the //output all of the columns within the rowrow

for (int c=1; c<=width/2; c++) {for (int c=1; c<=width/2; c++) {

if ( (r%2) == 0 )if ( (r%2) == 0 )System.out.print( " *" );System.out.print( " *" );

elseelse System.out.print( "* " System.out.print( "* " ););

}}

System.out.println();System.out.println();

}}

final int width = 8;final int width = 8;

//output all of the rows//output all of the rows

for (int r=1; r<=width; r++) {for (int r=1; r<=width; r++) {

//output all of the columns within the //output all of the columns within the rowrow

for (int c=1; c<=width/2; c++) {for (int c=1; c<=width/2; c++) {

if ( (r%2) == 0 )if ( (r%2) == 0 )

System.out.print( " *" );System.out.print( " *" );

elseelse

System.out.print( "* " );System.out.print( "* " );

}}

System.out.println();System.out.println();

}}

What are the possible values of r % 2?

How many values are possible with r % 2?

What data type has exactly this many values?

final int width = 8;final int width = 8;boolean bumpOver = false;boolean bumpOver = false;//output all of the rows//output all of the rowsfor (int r=1; r<=width; r++) {for (int r=1; r<=width; r++) { //output all of the columns within the //output all of the columns within the rowrow for (int c=1; c<=width/2; c++) {for (int c=1; c<=width/2; c++) {

if (bumpOver)if (bumpOver) System.out.print( " *" );System.out.print( " *" );elseelse System.out.print( "* " );System.out.print( "* " );

}} System.out.println();System.out.println(); bumpOver = !bumpOver;bumpOver = !bumpOver;}}

Use a boolean instead of mod.

final int width = 8;final int width = 8;boolean bumpOver = false;boolean bumpOver = false;//output all of the rows//output all of the rowsfor (int r=1; r<=width; r++) {for (int r=1; r<=width; r++) { //output all of the columns within the //output all of the columns within the rowrow for (int c=1; c<=width/2; c++) {for (int c=1; c<=width/2; c++) {

if (bumpOver)if (bumpOver) System.out.print( " *" );System.out.print( " *" );elseelse System.out.print( "* " );System.out.print( "* " );

}} System.out.println();System.out.println(); bumpOver = !bumpOver;bumpOver = !bumpOver;}}

Why width/2?

/*/* * file : CheckerBoard.java* file : CheckerBoard.java * author: george j. grevera, ph.d.* author: george j. grevera, ph.d. * desc. : program to output a checkerboard (problem 4.1, p. 74.* desc. : program to output a checkerboard (problem 4.1, p. 74. */*/public class CheckerBoard {public class CheckerBoard {

public static void main ( String[] s ) {public static void main ( String[] s ) {//declare variables & initialize i/o//declare variables & initialize i/o//ouput startup message//ouput startup messageSystem.out.println( "here's the checkerboard:\n" );System.out.println( "here's the checkerboard:\n" );

final int width = 8;final int width = 8;boolean bumpOver = false;boolean bumpOver = false;//output all of the rows//output all of the rowsfor (int r=1; r<=width; r++) {for (int r=1; r<=width; r++) { //output all of the columns within the row//output all of the columns within the row for (int c=1; c<=width/2; c++) {for (int c=1; c<=width/2; c++) {

if (bumpOver)if (bumpOver) System.out.print( " *" );System.out.print( " *" );elseelse System.out.print( "* " );System.out.print( "* " );

}} System.out.println();System.out.println(); bumpOver = !bumpOver;bumpOver = !bumpOver;}}

//finish up//finish upSystem.out.println( "\n\nadios" );System.out.println( "\n\nadios" );

}}}}

The complete program.

Let’s “draw” a Let’s “draw” a rectangle/box.rectangle/box.

Generate a rectangle.Generate a rectangle.

********************

* ** *

* ** * <- rows<- rows

* ** *

********************

^ cols^ cols

Generate a rectangle.Generate a rectangle.

********************* ** ** ** *<- rows<- rows* ** *********************

^ cols^ cols

Note that the first and last lines are the Note that the first and last lines are the same; also note that all of the middle lines same; also note that all of the middle lines are the same.are the same.

Generate a rectangle.Generate a rectangle.

********************* ** ** ** * <-rows<-rows* ** *********************

^ cols^ cols

So our algorithm is:So our algorithm is:1.1. Output the first line.Output the first line.2.2. Output the intervening lines.Output the intervening lines.3.3. Output the last line (just like the first).Output the last line (just like the first).

Generate a rectangle.Generate a rectangle.********************* ** ** ** * <-rows<-rows* ** *********************

^ cols^ cols

//Output the first line.//Output the first line.for (int c=0; c<cols; c++) {for (int c=0; c<cols; c++) {

System.out.print( "*" );System.out.print( "*" );}}System.out.println();System.out.println();

Generate a rectangle.Generate a rectangle.********************* ** ** ** * <-rows<-rows* ** *********************

^ cols^ cols//Output the intervening lines.//Output the intervening lines.for (int r=0; r<rows-2; r++) {for (int r=0; r<rows-2; r++) {

System.out.print( "*" );System.out.print( "*" );for (int c=0; c<cols-2; c++) {for (int c=0; c<cols-2; c++) {

System.out.print( " " );System.out.print( " " );}}System.out.println( "*" );System.out.println( "*" );

}}

Generate a rectangle.Generate a rectangle.********************* ** ** ** * <-rows<-rows* ** *********************

^ cols^ cols

//Output the last line (just like the first).//Output the last line (just like the first).for (int c=0; c<cols; c++) {for (int c=0; c<cols; c++) {

System.out.print( "*" );System.out.print( "*" );}}System.out.println();System.out.println();

final int rows = 10;final int rows = 10; //define number of rows//define number of rowsfinal int cols = 20;final int cols = 20; //define number of columns//define number of columns//Output the first line (just like the last).//Output the first line (just like the last).for (int c=0; c<cols; c++) {for (int c=0; c<cols; c++) {

System.out.print( "*" );System.out.print( "*" );}}System.out.println();System.out.println();

//Output the intervening lines.//Output the intervening lines.for (int r=0; r<rows-2; r++) {for (int r=0; r<rows-2; r++) {

System.out.print( "*" );System.out.print( "*" );for (int c=0; c<cols-2; c++) {for (int c=0; c<cols-2; c++) {

System.out.print( " " );System.out.print( " " );}}System.out.println( "*" );System.out.println( "*" );

}}//Output the last line (just like the first).//Output the last line (just like the first).for (int c=0; c<cols; c++) {for (int c=0; c<cols; c++) {

System.out.print( "*" );System.out.print( "*" );}}System.out.println();System.out.println();

Repeatedly prompt until Repeatedly prompt until user enters something user enters something

valid.valid.final intfinal int minimum = 0;minimum = 0;

intint inputValue = inputValue = minimum-1;minimum-1;

while (inputValue < minimum) while (inputValue < minimum) {{

inputValue = in.nextInt();inputValue = in.nextInt();

}}

Repeatedly prompt until Repeatedly prompt until user enters something user enters something

valid.valid.final intfinal int minimum = 0;minimum = 0;intint inputValue = minimum-1;inputValue = minimum-1;booleanboolean invalid = true;invalid = true;while (invalid) {while (invalid) {

inputValue = in.nextInt();inputValue = in.nextInt();if (inputValue >= minimum) {if (inputValue >= minimum) {

invalid = false;invalid = false;}}

}}

Repeatedly prompt until Repeatedly prompt until user enters something user enters something

valid.valid.final intfinal int minimum = 0;minimum = 0;intint inputValue = minimum-1;inputValue = minimum-1;booleanboolean valid = false;valid = false;while (!valid) {while (!valid) {

inputValue = in.nextInt();inputValue = in.nextInt();if (inputValue >= minimum) {if (inputValue >= minimum) {

valid = true;valid = true;}}

}}

Shakespearean insultsShakespearean insults

p. 75 of Per Brinch Hansen’s Java book (if p. 75 of Per Brinch Hansen’s Java book (if time permits).time permits).

Thou goatish, hasty-witted ratsbane!Thou goatish, hasty-witted ratsbane! Thou loggerheaded, doghearted dewberry!Thou loggerheaded, doghearted dewberry! Thou churlish, tickle-brained pigeon-egg!Thou churlish, tickle-brained pigeon-egg!

Our task is to prompt the user for the number Our task is to prompt the user for the number of these to output, and then output that of these to output, and then output that number of insults.number of insults.

Shakespearean insultsShakespearean insults ThouThou goatish,goatish, hasty-wittedhasty-witted

ratsbane!ratsbane! ThouThou loggerheaded,loggerheaded, doghearteddoghearted dewberry!dewberry! ThouThou churlish,churlish, tickle-brainedtickle-brained pigeon-egg!pigeon-egg!

always always

pick one pick one pick one

Shakespearean insultsShakespearean insultsColumn 1Column 1 Column 2Column 2 Column 3Column 3

artlessartless beetle-headedbeetle-headed barnaclebarnacle

bootlessbootless clay-brainedclay-brained coxcombcoxcomb

churlishchurlish doghearteddoghearted dewberrydewberry

dissemblingdissembling fly-bittenfly-bitten foot-lickerfoot-licker

erranterrant hasty-wittedhasty-witted gudgeongudgeon

fobbingfobbing idle-headedidle-headed joltheadjolthead

goatishgoatish rough-hewnrough-hewn loutlout

impertinentimpertinent swag-belliedswag-bellied minnowminnow

jarringjarring tickle-brainedtickle-brained pigeon-eggpigeon-egg

loggerheadedloggerheaded weather-weather-bittenbitten

ratsbaneratsbane

Shakespearean insults Shakespearean insults algorithmalgorithm

1.1. Prompt user for number of insults.Prompt user for number of insults.2.2. Read in the number of insults.Read in the number of insults.3.3. Output that number of insults.Output that number of insults.

1.1. Output “Thou ”.Output “Thou ”.2.2. Pick and output a word from column 1.Pick and output a word from column 1.3.3. Output “,”.Output “,”.4.4. Pick and output a word from column 2.Pick and output a word from column 2.5.5. Output “ ”.Output “ ”.6.6. Pick and output a word from column 3.Pick and output a word from column 3.7.7. Output “!” w/ newline.Output “!” w/ newline.

Shakespearean insults Shakespearean insults algorithmalgorithm

//Prompt user for number of insults.//Prompt user for number of insults.//Read in the number of insults.//Read in the number of insults.//Output that number of insults.//Output that number of insults.

//Output “Thou ”.//Output “Thou ”.//Pick and output a word from column 1.//Pick and output a word from column 1.//Output “,”.//Output “,”.//Pick and output a word from column 2.//Pick and output a word from column 2.//Output “ ”.//Output “ ”.//Pick and output a word from column 3.//Pick and output a word from column 3.//Output “!” w/ newline.//Output “!” w/ newline.

Shakespearean insults Shakespearean insults algorithmalgorithm

Scanner in = new Scanner( System.in Scanner in = new Scanner( System.in ););

//Prompt user for number of insults.//Prompt user for number of insults.

System.out.print( "Enter the number System.out.print( "Enter the number of insults: " );of insults: " );

//Read in the number of insults.//Read in the number of insults.

final int count = in.nextInt();final int count = in.nextInt();

Shakespearean insults Shakespearean insults algorithmalgorithm

//Output that number of insults.//Output that number of insults.for (int i=0; i<count; i++) {for (int i=0; i<count; i++) {

//Output “Thou ”.//Output “Thou ”.//Pick and output a word from column 1.//Pick and output a word from column 1.//Output “, ”.//Output “, ”.//Pick and output a word from column 2.//Pick and output a word from column 2.//Output “ ”.//Output “ ”.//Pick and output a word from column 3.//Pick and output a word from column 3.//Output “!” w/ newline.//Output “!” w/ newline.

}}

//Output that number of insults.//Output that number of insults.for (int i=0; i<count; i++) {for (int i=0; i<count; i++) {

//Output “Thou ”.//Output “Thou ”.System.out.print( “Thou ” );System.out.print( “Thou ” );//Pick and output a word from column 1.//Pick and output a word from column 1.??//Output “, ”.//Output “, ”.System.out.print( “, ” );System.out.print( “, ” );//Pick and output a word from column 2.//Pick and output a word from column 2.??//Output “ ”.//Output “ ”.//Pick and output a word from column 3.//Pick and output a word from column 3.??//Output “!” w/ newline.//Output “!” w/ newline.System.out.println( “!” );System.out.println( “!” );

}}

//Output that number of insults.//Output that number of insults.Random rnd = new Random();Random rnd = new Random();for (int i=0; i<count; i++) {for (int i=0; i<count; i++) {

System.out.print( “Thou ” );System.out.print( “Thou ” );//Pick and output a word from column 1.//Pick and output a word from column 1.??System.out.print( “, ” );System.out.print( “, ” );//Pick and output a word from column 2.//Pick and output a word from column 2.??System.out.print( “ ” );System.out.print( “ ” );//Pick and output a word from column 3.//Pick and output a word from column 3.??

System.out.printSystem.out.printlnln( “!” );( “!” );}}

//Output that number of insults.//Output that number of insults.Random rnd = new Random();Random rnd = new Random();for (int i=0; i<count; i++) {for (int i=0; i<count; i++) {

System.out.print( “Thou ” );System.out.print( “Thou ” );//Pick and output a word from column 1.//Pick and output a word from column 1.switch (rnd.nextInt(10)+1) {switch (rnd.nextInt(10)+1) {

case 1:case 1: System.out.print( “artless”)System.out.print( “artless”)break;break;case 2:case 2: System.out.print( “bootless”);System.out.print( “bootless”);break;break;……default:default: System.out.print( “loggerheaded”);System.out.print( “loggerheaded”);break;break;

} //end switch} //end switch

//Output that number of insults.//Output that number of insults.Random rnd = new Random();Random rnd = new Random();for (int i=0; i<count; i++) {for (int i=0; i<count; i++) {

System.out.print( “Thou ” );System.out.print( “Thou ” );//Pick and output a word from column 1.//Pick and output a word from column 1.switch (rnd.nextInt(10)+1) {switch (rnd.nextInt(10)+1) {

case 1:case 1:System.out.print( “artless”)System.out.print( “artless”) break;break;case 2:case 2:System.out.print( “bootless”);System.out.print( “bootless”); break;break;……default:default: System.out.print( “loggerheaded”);System.out.print( “loggerheaded”); break;break;

} //end switch} //end switchSystem.out.print( “, ” );System.out.print( “, ” );//Pick and output a word from column 2.//Pick and output a word from column 2.??System.out.print( “ ” );System.out.print( “ ” );//Pick and output a word from column 3.//Pick and output a word from column 3.??System.out.println( “!” );System.out.println( “!” );

}}

//Pick and output a word from column 1.//Pick and output a word from column 1.switch (rnd.nextInt(10)+1) {switch (rnd.nextInt(10)+1) {

case 1:case 1: System.out.print( “artless”)System.out.print( “artless”) break;break;case 2:case 2: System.out.print( “bootless”);System.out.print( “bootless”); break;break;……default:default: System.out.print( “loggerheaded”);System.out.print( “loggerheaded”);break;break;

} //end switch} //end switchSystem.out.print( “, ” );System.out.print( “, ” );//Pick and output a word from column 2.//Pick and output a word from column 2.switch (rnd.nextInt(10)+1) {switch (rnd.nextInt(10)+1) {

case 1:case 1: System.out.print( “beetle-headed”)System.out.print( “beetle-headed”) break;break;case 2:case 2: System.out.print( “clay-brained”);System.out.print( “clay-brained”); break;break;……default:default: System.out.print( “weather-bitten”);System.out.print( “weather-bitten”); break;break;

} //end switch} //end switchSystem.out.print( “ ” );System.out.print( “ ” );//Pick and output a word from column 3.//Pick and output a word from column 3.……

//Output that number of insults.//Output that number of insults.Random rnd = new Random();Random rnd = new Random();for (int i=0; i<count; i++) {for (int i=0; i<count; i++) {

System.out.print( “Thou ” );System.out.print( “Thou ” );//Pick and output a word from column 1.//Pick and output a word from column 1.switch (rnd.nextInt(10)+1) {switch (rnd.nextInt(10)+1) {

case 1:case 1: System.out.print( “artless”)System.out.print( “artless”) break;break;case 2:case 2: System.out.print( “bootless”);System.out.print( “bootless”); break;break;……default:default:System.out.print( “loggerheaded”);System.out.print( “loggerheaded”); break;break;

} //end switch} //end switchSystem.out.print( “, ” );System.out.print( “, ” );//Pick and output a word from column 2.//Pick and output a word from column 2.switch (rnd.nextInt(10)+1) {switch (rnd.nextInt(10)+1) {

case 1:case 1: System.out.print( “beetle-headed”)System.out.print( “beetle-headed”) break;break;case 2:case 2: System.out.print( “clay-brained”);System.out.print( “clay-brained”); break;break;……default:default:System.out.print( “weather-bitten”);System.out.print( “weather-bitten”); break;break;

} //end switch} //end switchSystem.out.print( “ ” );System.out.print( “ ” );//Pick and output a word from column 3.//Pick and output a word from column 3.??System.out.println( “!” );System.out.println( “!” );

}}

And similarly here.