50 likes | 141 Views
Learn about loop designing concepts like while and for loops, error debugging, nested loops, and practical exercises in 2D arrays. Understand count-controlled vs. sentinel-based looping strategies for efficient coding. Discover common errors like off-by-one and infinite loops, and practice with exercises on drawing shapes. Advance your programming skills with loop intricacies and challenges.
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 – * ** *** ****