Saturday, October 24, 2009

I am learning about nested loops in java can anyone give me an explanation in their own words?

A nested loop is a inner loop encased in the loop body of another outer loop. The inner or outer loop can be any type: while, do while, or for.





Say you wanted to output some rows and columns in the shape of a box, say a box made up of asteriks ie. stars.





You want the box to be 10 stars wide, and 10 stars deep. Those are your terminating conditions. A good way to handle it, instead of having ten statements for each row of stars and 10 for each column is to loop 10 times for each row and 10 times for each column. The pseudocode for that nested loop would look like this:





Begin Program


Do While columnNum %26lt;= 10 //the outer loop


Do While rowNum %26lt;= 10 //the inner loop


Print "*";


intRowNum = intRowNum + 1 //increment to next row


Loop //end of inner loop





rowNum = 1 // initialize rowNum for the next outer


columnNum = intColumnNum + 1 //increment to next column


Loop //end of the outter loop


End Program





There is a worked example of the same problem here using the for statement in java which should help cement the concept http://www.cs.umd.edu/~clin/MoreJava/Con...

I am learning about nested loops in java can anyone give me an explanation in their own words?
A loop inside of a loop....



Loose Teeth

No comments:

Post a Comment