Programming Fundamentals/Loops

From Wikiversity
Jump to navigation Jump to search
Flowchart Conditions

This lesson introduces loops, including while, for, and do loops. A loop is a sequence of instructions designed to be repeated until a certain condition is met or achieved. Loops only need to be written once, but repeat multiple times over. Loops are typically used to do certain tasks multiple times based on the program's task, avoiding having to create extra, unnecessary steps in a program:

  • While loops
  • Do loops
  • For loops

While loops are used when the program is designed to count the iterations by itself. Do loops are designed to continue a section of code until a condition is met, testing to see if the condition is met between iterations. For loops are designed to have a controlled amount of loops, where the number of times a loop must repeat is already decided, unlike the other two where a condition must be met to exit and continue to the rest of the program.[source?]

Objectives and Skills[edit]

Objectives and skills for this lesson include:

  • Understand while and do while loops
  • Understand for and foreach loops
  • Use loops to implement program functionality
  • Understand when to use each type of loop

Readings[edit]

  1. Rebus: Programming Fundamentals
  2. Wikipedia: Control flow

Multimedia[edit]

  1. YouTube: Programming For Beginners - 'while' loops
  2. YouTube: Programming For Beginners - 'for' loops
  3. YouTube: Introduction to Programming - Iteration
  4. YouTube: For Loop - Processing Tutorial
  5. YouTube: While Loop - Processing Tutorial
  6. YouTube: 6.6: Nested Loops - Processing Tutorial
  7. YouTube: Basic for For Loops and Nesting Loops
  8. YouTube: Nested Loops - Processing Tutorial
  9. YouTube : Loops - Four styles - While, For, Do While, Repeat Until

Examples[edit]

Activities[edit]

Complete the following activities using pseudocode, a flowcharting tool, or your selected programming language. Use separate functions for input, each type of processing, and output. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.

While Loops[edit]

Complete the following using a while loop structure.

  1. Create a program that uses a loop to generate a list of multiplication expressions for a given value. Ask the user to enter the value and the number of expressions to be displayed. For example, a list of three expressions for the value 1 would be:
        1 * 1 = 1
        1 * 2 = 2
        1 * 3 = 3
    A list of five expressions for the value 3 would be:
        3 * 1 = 3
        3 * 2 = 6
        3 * 3 = 9
        3 * 4 = 12
        3 * 5 = 15
  2. Review MathsIsFun: Definition of Average. Create a program that asks the user to enter grade scores. Start by asking the user how many scores they would like to enter. Then use a loop to request each score and add it to a total. Finally, calculate and display the average for the entered scores.
  3. Review MathsIsFun: Pi. Write a program that uses the Nilakantha series to calculate Pi based on a given number of iterations entered by the user.

Do While / Repeat Until Loops[edit]

Complete the following using a do while / repeat until loop structure.

  1. Review MathsIsFun: Definition of Average. Create a program that asks the user to enter grade scores. Use a loop to request each score and add it to a total. Continue accepting scores until the user enters no value (empty input). Finally, calculate and display the average for the entered scores.
  2. Review Khan Academy: A guessing game. Write a program that allows the user to think of a number between 0 and 100, inclusive. Then have the program try to guess their number. Start at the midpoint (50) and ask the user if their number is (h)igher, (l)ower, or (e)qual to the guess. If they indicate lower, guess the new midpoint (25). If they indicate higher, guess the new midpoint (75). Continue efficiently guessing higher or lower until they indicate equal, then print the number of guesses required to guess their number and end the program.
  3. Add a do while / repeat until loop to any activity from a previous chapter. Continue running the program while the user wants to continue or until the user wants to stop.
  4. Add an input validation loop to any activity from a previous chapter. Verify that the input is valid before returning the value. Ask the user to input the value again while the input is invalid.

For Loops[edit]

Complete the following using a for loop structure.

  1. Create a program that uses a loop to generate a list of multiplication expressions for a given value. Ask the user to enter the value and the number of expressions to be displayed. For example, a list of three expressions for the value 1 would be:
        1 * 1 = 1
        1 * 2 = 2
        1 * 3 = 3
    A list of five expressions for the value 3 would be:
        3 * 1 = 3
        3 * 2 = 6
        3 * 3 = 9
        3 * 4 = 12
        3 * 5 = 15
  2. Review MathsIsFun: Definition of Average. Create a program that asks the user to enter grade scores. Start by asking the user how many scores they would like to enter. Then use a loop to request each score and add it to a total. Finally, calculate and display the average for the entered scores.
  3. Review MathsIsFun: Pi. Write a program that uses the Nilakantha series to calculate Pi based on a given number of iterations entered by the user.

Nested Loops[edit]

Complete the following using a nested loop structure.

  1. Review MathsIsFun: 10x Printable Multiplication Table. Create a program that uses nested loops to generate a multiplication table. Rather than simply creating a 10 by 10 table, ask the user to enter the starting and ending values. Include row and column labels. For example, the output from 1 to 3 might look like:
            1   2   3
        1   1   2   3
        2   2   4   6
        3   3   6   9
    The output from 3 to 5 might look like:
            3   4   5
        3   9  12  15
        4  12  16  20
        5  15  20  25
    Use separate subroutines/functions/methods for input, processing, and output. Avoid global variables by passing parameters and returning results.
  2. Add a do while / repeat until loop to any activity from this chapter. Continue running the program while the user wants to continue or until the user wants to stop.

Lesson Summary[edit]

  • Control flow refers to the order in which the individual statements, instructions or function calls of an imperative or a declarative program are executed or evaluated.[1]
  • Control flow statement types include unconditional branch, conditional branch, conditional loop, subroutines, and unconditional halt.[2]
  • A loop is a sequence of statements which is specified once but which may be carried out several times in succession.[3]
  • Do while is a test after control structure. A do while loop will run at least once, and will test the given condition after each execution.[source?]
  • There are two commonly used test before loops in the iteration (or repetition) category of control structures. They are: while and for.[4]
  • While loops are used when the code inside the loop will determine how many iterations are required.[5]
  • For loops are used when it is known before the loop starts how many iterations are required.[6]
  • Within the while control structure there are four attributes to a properly working loop. They are:[7]
    • Initializing the flag
    • Test expression
    • Action or actions
    • Update of the flag
  • Within the do while control structure there are three attributes to a properly working loop. They are:[8]
    • Action or actions
    • Update of the flag
    • Test expression
  • Within the for control structure, there are four attributes to a properly working loop. They are:[9]
    • Initializing the flag - done once
    • Test expression
    • Action or actions
    • Update of the flag
  • Goto is usually not considered to be good programming structure. However, a few programming languages will allow you the ability to create a label with an identifier name followed by a colon.[source?]
  • Good programming always provides for a method to ensure that the loop question will eventually be false so that the loop will stop executing and the program continues with the next line of code. Otherwise, the program can get into an infinite loop.[10]

Key Terms[edit]

break
A branching function that terminates the existing structure.[11]
condition
The statement a loop checks in order to decide if it should loop again or stop looping.[12]
continue
A branching function that causes a loop to stop its current iteration and begin the next one.[13]
counting controlled
A loop where a variable predetermines how many times a loop will run.[14]
do while loop
A do while loop is a control flow statement that executes a block of code at least once, and then repeatedly executes the block, or not, depending on a given boolean condition at the end of the block.[15]
exit
A predefined function used to prematurely stop a program and return to the operating system.[16]
flag
commonly used to control or to indicate the intermediate state or outcome of a particular operation[17]
for loop
A for loop is a control flow statement for specifying iteration, which allows code to be executed repeatedly. A for loop has two parts: a header specifying the iteration, and a body which is executed once per iteration.[18]
foreach loop
For each (or foreach, sometimes called an iterative for-loop) is a control flow statement for traversing items in a collection.[19]
goto
An unstructured branching statement that makes the logic in a program to jump around to a different location[20]
infinite loop (or endless loop)
A sequence of instructions in a computer program which loops endlessly, either due to the loop having no terminating condition or having one that can never be met.[21]
iteration control structure
A statement or block is executed until the program reaches a certain state, or operations have been applied to every element of a collection.[22]
nested loop
Places one loop inside of another loop. The inner loop will repeat depending on the number of iterations of the outer loop.[23]
return
A branching statement that causes a function to jump back to the function that called it. Allowing it to be also used as a way to break out of a loop.[24]
while loop
A while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition.[25]

Assessments[edit]

See Also[edit]

References[edit]

  1. Wikipedia: Control flow
  2. Wikipedia: Control flow
  3. Wikipedia: Control flow
  4. https://press.rebus.community/programmingfundamentals/chapter/while-loop/
  5. https://press.rebus.community/programmingfundamentals/chapter/while-loop/
  6. https://press.rebus.community/programmingfundamentals/chapter/for-loop/
  7. https://press.rebus.community/programmingfundamentals/chapter/while-loop/
  8. https://press.rebus.community/programmingfundamentals/chapter/do-while-loop/
  9. https://press.rebus.community/programmingfundamentals/chapter/for-loop/
  10. Programing Fundamentals (Kenneth Leroy Busbee and Dave Braunschweigh)
  11. https://press.rebus.community/programmingfundamentals/chapter/branching-statements/
  12. Wikipedia: Conditional (computer programming)
  13. https://press.rebus.community/programmingfundamentals/chapter/branching-statements/
  14. http://www.cs.iit.edu/~cs561/cs115/looping/count.html
  15. https://press.rebus.community/programmingfundamentals/chapter/do-while-loop/
  16. https://press.rebus.community/programmingfundamentals/chapter/branching-statements/
  17. https://press.rebus.community/programmingfundamentals/chapter/flag-concept/
  18. https://press.rebus.community/programmingfundamentals/chapter/for-loop/
  19. https://en.wikipedia.org/wiki/Foreach_loop
  20. https://press.rebus.community/programmingfundamentals/chapter/branching-statements/
  21. Wikipedia: Infinite loop
  22. https://press.rebus.community/programmingfundamentals/chapter/iteration-control-structures/
  23. https://press.rebus.community/programmingfundamentals/chapter/nested-for-loops/
  24. https://press.rebus.community/programmingfundamentals/chapter/return-statement/
  25. https://press.rebus.community/programmingfundamentals/chapter/while-loop/