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.
Objectives and Skills
[edit | edit source]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 | edit source]Multimedia
[edit | edit source]- YouTube: Programming For Beginners - 'while' loops
- YouTube: Programming For Beginners - 'for' loops
- Youtube: Intro to Programming: Loops
- Youtube: Intro to Programming - Loops
- YouTube: Introduction to Programming - Iteration
- Youtube: Loops - Coding Basics
- YouTube: For Loop - Processing Tutorial
- YouTube: While Loop - Processing Tutorial
- YouTube: 6.6: Nested Loops - Processing Tutorial
- YouTube: Basic for For Loops and Nesting Loops
- YouTube: Nested Loops - Processing Tutorial
- YouTube : Loops - Four styles - While, For, Do While, Repeat Until
- Youtube: Control Structures - while loop - do-while loop - for loop - Goto - break - continue statements
Practice
[edit | edit source]Examples
[edit | edit source]Activities
[edit | edit source]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 | edit source]Complete the following using a while loop structure.
- 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
- 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.
- 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.
- 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 | edit source]Complete the following using a do while / repeat until loop structure.
- 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.
- 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.
- 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.
- 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 | edit source]Complete the following using a for loop structure.
- 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
- 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.
- 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.
- 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 | edit source]Complete the following using a nested loop structure.
- 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. - 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 | edit source]- 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.
- 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.
- 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 | edit source]- 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 | edit source]See Also
[edit | edit source]- Introduction to Programming/Control structures
- Programming Logic/Looping
- Wikipedia: While loop
- Wikipedia: For loop
- Wikipedia: Do while loop
- Wikipedia: Foreach loop
- Wikipedia: Infinite loop
References
[edit | edit source]- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ https://press.rebus.community/programmingfundamentals/chapter/while-loop/
- ↑ https://press.rebus.community/programmingfundamentals/chapter/while-loop/
- ↑ https://press.rebus.community/programmingfundamentals/chapter/for-loop/
- ↑ https://press.rebus.community/programmingfundamentals/chapter/while-loop/
- ↑ https://press.rebus.community/programmingfundamentals/chapter/do-while-loop/
- ↑ https://press.rebus.community/programmingfundamentals/chapter/for-loop/
- ↑ Programing Fundamentals (Kenneth Leroy Busbee and Dave Braunschweigh)
- ↑ https://press.rebus.community/programmingfundamentals/chapter/branching-statements/
- ↑ Wikipedia: Conditional (computer programming)
- ↑ https://www.computerhope.com/jargon/c/contstat.htm
- ↑ https://press.rebus.community/programmingfundamentals/chapter/branching-statements/
- ↑ https://www.tutorialspoint.com/cprogramming/c_continue_statement.htm
- ↑ http://www.cs.iit.edu/~cs561/cs115/looping/count.html
- ↑ https://press.rebus.community/programmingfundamentals/chapter/do-while-loop/
- ↑ https://press.rebus.community/programmingfundamentals/chapter/branching-statements/
- ↑ http://vhdl.renerta.com/mobile/source/vhd00028.htm
- ↑ https://press.rebus.community/programmingfundamentals/chapter/flag-concept/
- ↑ https://techterms.com/definition/flag
- ↑ https://press.rebus.community/programmingfundamentals/chapter/for-loop/
- ↑ https://en.wikipedia.org/wiki/Foreach_loop
- ↑ https://press.rebus.community/programmingfundamentals/chapter/branching-statements/
- ↑ Wikipedia: Infinite loop
- ↑ https://press.rebus.community/programmingfundamentals/chapter/iteration-control-structures/
- ↑ https://press.rebus.community/programmingfundamentals/chapter/nested-for-loops/
- ↑ https://press.rebus.community/programmingfundamentals/chapter/return-statement/
- ↑ https://www.lua.org/pil/4.4.html
- ↑ https://press.rebus.community/programmingfundamentals/chapter/while-loop/