460 likes | 1.28k Views
Nested Loops. CSIS 1595: Fundamentals of Programming and P roblem Solving 1. Nested Loops. Often nest one loop inside another Syntax: while/for of outer loop statements in outer loop while/for of inner loop statements in inner loop more statements in outer loop
E N D
Nested Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1
Nested Loops • Often nest one loop inside another • Syntax:while/for of outer loopstatements in outer loopwhile/for of inner loop statements in inner loop more statements in outer loop • Note that indentation defines what is in inner, outer loop Inner loop run for all cycles For each cycle of outer loop
Example Nested Loop • All three cycles of inner loop executed each time outer loop executed
Modified Trip Mileage Example • Original goal: Keep track of total mileage driven on trip • Additional goals: • Use loop to validate miles entered to insure positive number • Use loop to show “odometer” during this stage of trip
Incremental Development • If each loop “separate” concept, should build and test one loop at a time • Develop inner loops first, and then put in outer loop (executing inner loop once) • Develop outer loop first, and then add inner loops • Sometimes easier, since don’t have to change indentation
Printing 2-Dimensional Tables • Goal: Print data based on two different components • Example: Tax table based on both income and dependents • Idea: • Each time through outer loop prints entire row • May want to print row header first in loop • Each time through inner loop prints a column in that row
Printing 2-Dimensional Tables • Multiplication table for all X and Y between 1 and 5 • Strategy: • Outer loop runs Y from 1 to 5 • Inner loop runs X from 1 to 5 for each X • Computes and prints X * Y for that X, Y pair • Problem: Must print tab for each print, not end of line • Solution: Use end=“\t” as argument to print • Will also need to print end of line after each row • Use print(“”)at end of outer loop to do this
Row and Column Headers • Often want to print labels for each row, column • Strategy: • Use loop beforeouter loop to print column headers • Print additional tab first to leave space for row labels • Print row value at start of each outer loop cycle • Before starting inner loop for that cycle