Programming Fundamentals/Loops

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 may 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. Here's a brief explanation of each loop.:

  • While loops are used when the program is designed to count the iterations by itself, which can set up the loop in the program based on the user's input.
  • 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. This is similar to while loops because they also make it easier to set up the condition's loop based on the user's input.
  • 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.
Flowchart Conditions
Flowchart Conditions

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. Pressbooks: Programming Fundamentals
  2. Wikipedia: Control flow

Multimedia

edit
  1. YouTube: Programming For Beginners - 'while' loops
  2. YouTube: Programming For Beginners - 'for' loops
  3. Youtube: Intro to Programming: Loops
  4. Youtube: Intro to Programming - Loops
  5. YouTube: Introduction to Programming - Iteration
  6. Youtube: Loops - Coding Basics
  7. YouTube: For Loop - Processing Tutorial
  8. YouTube: While Loop - Processing Tutorial
  9. YouTube: 6.6: Nested Loops - Processing Tutorial
  10. YouTube: Basic for For Loops and Nesting Loops
  11. YouTube: Nested Loops - Processing Tutorial
  12. YouTube : Loops - Four styles - While, For, Do While, Repeat Until
  13. Youtube: Control Structures - while loop - do-while loop - for loop - Goto - break - continue statements

Practice

edit

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.
  4. Review MathsIsFun: Fibonacci Sequence. Write a program that displays the Fibonacci sequence 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 either a negative value or no value (your choice). 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.
  4. Review MathsIsFun: Fibonacci Sequence. Write a program that displays the Fibonacci sequence 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] It's a set of rules performed if a certain condition is met. It is sometimes referred to as an If-Then statement, because IF a condition is met, THEN an action is performed.[13]
continue
A branching function that causes a loop to stop its current iteration and begin the next one.[14] It works like a break statement but instead of forcing termination, it forces the next iteration of the loop to take place, skipping any code in between.[15]
counting controlled
A loop where a variable (such as a counter) predetermines how many times a loop will run.[16]
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.[17]
exit
A predefined function used to prematurely stop a program and return to the operating system.[18] It is used to finish or exit the execution of an enclosing loop statement. If the statement includes a condition, then the exit from the loop is conditional.[19]
flag
commonly used to control or to indicate the intermediate state or outcome of a particular operation[20] It is the value that acts as a signal for a function or process. The value is used to determine the next step of a program.[21]
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.[22]
foreach loop
For each (or foreach, sometimes called an iterative for-loop) is a control flow statement for traversing items in a collection.[23]
goto
An unstructured branching statement that makes the logic in a program jump around to a different location[24]
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.[25]
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.[26]
nested loop
Places one loop inside of another loop. The inner loop will repeat depending on the number of iterations of the outer loop.[27]
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.[28] A return statement returns occasional results from a function or simply finishes a function. There is an implicit return at the end of any function, so you do not need to use one if your function ends naturally, without returning any value.[29]
while loop
A while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition.[30]

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://www.computerhope.com/jargon/c/contstat.htm
  14. https://press.rebus.community/programmingfundamentals/chapter/branching-statements/
  15. https://www.tutorialspoint.com/cprogramming/c_continue_statement.htm
  16. http://www.cs.iit.edu/~cs561/cs115/looping/count.html
  17. https://press.rebus.community/programmingfundamentals/chapter/do-while-loop/
  18. https://press.rebus.community/programmingfundamentals/chapter/branching-statements/
  19. http://vhdl.renerta.com/mobile/source/vhd00028.htm
  20. https://press.rebus.community/programmingfundamentals/chapter/flag-concept/
  21. https://techterms.com/definition/flag
  22. https://press.rebus.community/programmingfundamentals/chapter/for-loop/
  23. https://en.wikipedia.org/wiki/Foreach_loop
  24. https://press.rebus.community/programmingfundamentals/chapter/branching-statements/
  25. Wikipedia: Infinite loop
  26. https://press.rebus.community/programmingfundamentals/chapter/iteration-control-structures/
  27. https://press.rebus.community/programmingfundamentals/chapter/nested-for-loops/
  28. https://press.rebus.community/programmingfundamentals/chapter/return-statement/
  29. https://www.lua.org/pil/4.4.html
  30. https://press.rebus.community/programmingfundamentals/chapter/while-loop/