# 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

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

## Activities

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

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

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

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

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

• 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.
• Control flow statement types include unconditional branch, conditional branch, conditional loop, subroutines, and unconditional halt.
• A loop is a sequence of statements which is specified once but which may be carried out several times in succession.
• 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.
• While loops are used when the code inside the loop will determine how many iterations are required.
• For loops are used when it is known before the loop starts how many iterations are required.
• Within the while control structure there are four attributes to a properly working loop. They are:
• 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:
• 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:
• 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.

## Key Terms

break
A branching function that terminates the existing structure.
condition
The statement a loop checks in order to decide if it should loop again or stop looping. 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.
continue
A branching function that causes a loop to stop its current iteration and begin the next one. 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.
counting controlled
A loop where a variable (such as a counter) predetermines how many times a loop will run.
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.
exit
A predefined function used to prematurely stop a program and return to the operating system. 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.
flag
commonly used to control or to indicate the intermediate state or outcome of a particular operation 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.
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.
foreach loop
For each (or foreach, sometimes called an iterative for-loop) is a control flow statement for traversing items in a collection.
goto
An unstructured branching statement that makes the logic in a program jump around to a different location
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.
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.
nested loop
Places one loop inside of another loop. The inner loop will repeat depending on the number of iterations of the outer loop.
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. 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.
while loop
A while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition.