50 likes | 123 Views
Designing Loops. 3.4. Repeat “ numTimes ” many times. while loop int count = 0; while(count < numTimes ) { //execute statement(s) count++; } for loop equivalent for(int i = 0; i < numTimes; i++) //execute statement(s). Ending a Loop.
E N D
Designing Loops 3.4
Repeat “numTimes” many times • while loop intcount = 0; while(count < numTimes) { //execute statement(s) count++; } • for loop equivalent for(int i = 0; i < numTimes; i++) //execute statement(s)
Ending a Loop • List headed by size (known number of iterations) – count-controlled loop • Ask before iterating (would you like to continue? (y/n)) • List ended with sentinel value – see example from yesterday • Running out of input – used when getting input from files
Debugging Loops • Off by one errors • Infinite loops • Localize the problem • Trace variables
Nested for loops • Used to process 2 dimensional data • Especially 2-D arrays which are discussed in APCS and CMB • Exercise 1: Draw an nxn square that looks like – * * * * * * * * * • Exercise 2: Draw a triangle with base n that looks like – * ** *** **** • Challenge: Draw a triangle with base n that looks like – * ** *** ****