Open main menu

This lesson introduces loops, including while, for, and do loops.

Objectives and SkillsEdit

Objectives and skills for this lesson include:[1]

  • Construct and analyze code segments that perform iteration
    • while; for; break; continue; pass; nested loops and loops that include compound conditional expressions

ReadingsEdit

MultimediaEdit

ExamplesEdit

ActivitiesEdit

  1. Extend the BMI program from the previous lesson. Rather than terminating the program on invalid input, display an error message and ask the user to enter valid input. Provide a way for the user to terminate the program instead if they choose.
  2. Extend the BMI program above. Add a loop to the main program that continues asking for input after displaying each BMI result. Provide a way for the user to terminate the program instead if they choose.
  3. Update program and function documentation, consistent with the documentation standards for your selected programming language.
  4. Create a program that displays a BMI table, with columns for height from 58 inches to 76 inches in 2-inch increments and rows for weight from 100 pounds to 250 pounds in 10-pound increments. Reuse the conversion/calculation functions from the BMI program above. Include appropriate program and function documentation, consistent with the documentation standards for your selected programming language.
  5. Extend the fuel consumption MPG program from "Functions Chapter". Add a table showing how much fuel consumption grows and MPGs drop when the vehicle speed is higher. Review following article http://www.mpgforspeed.com/, the percentage of additional fuel consumption increases as the car goes faster, but the automotive world created an approximate formula which says that (starting from 55 mph) each mph driven faster makes fuel consumption grow 1%. Create a table showing vehicle consumption/MPGs starting from 55mph up to 85mph with 3mph increment. Allow the users to input the base mpg of their vehicle at speed of 55mpg (highway mpg).
  6. Review the GPA calculator program to ask the user how many classes they have. Then have the program ask the user for their grades in letters. Calculate and display their GPA. Then, create a letter table with columns for GPA scores (A = 4, C = 3) and rows for 50- 90%. Have the numbers increment by 1 and the percents be in 10 percent increments.
  7. Extend the Battleship program to display an error message for invalid input. Rather than terminating, ask the user to enter valid input. Provide a way for the user to terminate the program if they choose. Add a loop to the main program that continues asking the user to input the next ship until each player has selected valid positions for all of their ships. Update the program and function documentation, consistent with the documentation standards the class selected as their programming language. Create a function that displays a table of all positions on the board for each player and ship positions. Use different characters to indicate open spots and ship positions.

Lesson SummaryEdit

  • For loop is a control flow statement for specifying iteration, which allows code to be executed repeatedly.[2]
    • For-loop is known by a clear loop counter or loop variable which allows the body of the for loop to be repeatedly executed.[2]
    • For loop is typically used when the number of iterations is known before entering the loop.[2]
    • An optional step-value could be an increment or decrement may also be included in for loop.[2]
  • For-loop is commonly the source of an infinite loop since the fundamental steps of iteration are completely in the control of the programmer.[2]
  • Foreach loop means "do this to everything in this set", rather than "do this x times" which is what the traditional for loop means.[3]
    • Foreach loops usually maintain no explicit counter.[3]
    • Foreach loop avoids logical error and makes code simpler to read.[3]
  • When using a count-controlled loop to search through a table, it might be desirable to stop searching as soon as the required item is found. Some programming languages provide a statement such as break, which terminates the current loop immediately, and transfers control to the statement immediately after that loop.[4]
  • A loop variant is an integer expression which has an initial non-negative value.[4]
  • A loop invariant is an assertion which must be true before the first loop iteration and remain true after each iteration.[4]
  • Modern languages have a specialized structured construct for exception handling which does not rely on the use of GoTo or multi-level breaks or returns.[4]
  • Do-while loop is an exit-condition loop. This means that the code will enter the loop and then the condition will be evaluated, unlike while loops.[5]
  • A loop (like a Do-while loop) which checks its' condition after the execution of the loop body is called a post-test loop.[5]
  • A do-while loop is executed at least once and may continue to loop multiple times given the condition is true. It will loop until the given condition becomes false. In other words, in the event it doesn’t, an infinite loop will be created.[5]
  • Some languages use a different naming convention for this particular type of loop such as repeat until, while true, repeat while, and exit when.[5]
  • Often break statements are used with infinite loops to allow for termination.[5]
  • Continue statements suspend the current iteration and then resume as normal with the next iteration. If the iteration is the last one in the loop, the statement will end the entire loop early.[4]

Key TermsEdit

break
A keyword available in most languages (the functionality is near-ubiquitous regardless) that exits the innermost loop structure.[4]
continue
A keyword that suspends the current iteration and jumps directly onto the next.[4]
do-while loop
A post-test loop, meaning the body is guaranteed to execute at least once, as the condition is evaluated after the fact. Often post-test loops are indefinite loops, which iterate until a sentinel value gets encountered.[5]
for loop
A specialized loop for iterating a given number of times (definitely), usually featuring an encapsulated head of initialization, Boolean, and incrementation (or decrementation) components.[2]
for-each loop
A take on the for loop, where the definite iteration can occur directly over a collection or sequence of data, e.g. a list or an array, avoiding the possibility of an off-by-one error.[3]
infinite loop
A common pitfall where the user is locked into a never-ending process because of an unsatisfied terminating condition.[6]
loop counter
The variable that controls the iterations of a loop.[2]
nested loop
A loop that is enclosed by an outer, surrounding loop, useful when it has two or more dimensions of elements to parse.[4]
sentinel
A value that signals the completion of a process. An example is the EOF (end-of-file) marker present in many languages, representing not another character to read, but the end of the file and thus its processing.[7]
while loop
A pre-test loop, meaning there is no guarantee the body will execute. Like their do while counterparts, these loops are usually indefinite loops, iterating until a sentinel value gets encountered.[8]

See AlsoEdit

ReferencesEdit