Programming Fundamentals/Practice: Loops

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Chapter Summary[edit | edit source]

  • Iteration Control Structures - A statement or block is executed until the program reaches a certain state, or operations have been applied to every element of a collection.
  • While Loop - A control flow statement that allows code to be executed repeatedly based on a given Boolean condition.
  • Do While Loop - 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.
  • Flag Concept - A flag is a variable used to store information that will normally be used to control the program.
  • For Loop - A pretest loop that executes code repetitively until the condition evaluates to false. For loops are definite loops which are generally used as a counting loop when the number of iterations is known.
  • Branching Statements - Instructions in a computer program that can cause a computer to begin executing a different instruction sequence and thus deviate from its default behavior of executing instructions in order.
  • Increment and Decrement Operators - Unary operators that add or subtract one from their operand, respectively.
  • Integer Overflow - When an arithmetic operation attempts to create a numeric value that is outside of the range that can be represented with a given number of bits – either larger than the maximum or lower than the minimum representable value.
  • Nested Loops - Nested loops place one for loop inside another for loop. The inner loop is repeated for each iteration of the outer loop.

Review Questions[edit | edit source]

True / False[edit | edit source]

  1. The do-while and repeat until structure act exactly the same.
  2. Students sometimes confuse assignment and equality.
  3. The repeat until looping control structure is available in all programming languages.
  4. Because flags are often used, they are usually a special data type.
  5. The do-while is a test before the loop.
  6. Only for loops can be counting loops.
  7. The integer data type has modular arithmetic attributes.
  8. The escape code of \n is part of the formatting output.
  9. Nested for loops is not allowed in the C++ programming language.
  10. Counting loops use all four of the loop attributes.
  11. A Do While Loop is a block of statements that are executed one or more times before the expression is checked.
  12. In Python, While loops and Do While loops both use the While statement.
  13. Decrement is adding one to the value of a variable.
  14. a break is a predefined function used to prematurely stop a program and return to the operating system.
  15. A while loop will repeat a block of code indefinitely or until an exit command.
  16. The best loop for restarting your program is a While loop because the While loop will run through all the statements at least once before checking if the expression is true or not.
  17. a prefix increment adds one to the operator to the left of the operand.

Answers:

  1. false - The difference is that where the condition is checked
  2. true - Typically equality uses two equal signs instead of one.
  3. false - It is available in older languages more commonly than newer ones.
  4. false - Flags are used to control or indicate the intermediate state or outcome of particular operations.
  5. false - Do While loops are a test after iteration control structure, meaning they test after the loop has run at least once.
  6. false - Any kind of loop can be a counting loop.
  7. true
  8. true
  9. false - Nested loops involve a loop in another loop. They can be used in any language.
  10. true
  11. true
  12. true - The difference between the two is where the condition is checked.
  13. false - Increment is adding to the value of a variable.
  14. false - A break is a branching statement that terminates the existing structure.
  15. false - A Do While loop will repeat a block of code while true and exit with an exit command. While loop will loop indefinitely or condition is met.
  16. false - The While loop always checks the expression to see if it's true or not before running the associated statements, making it a terrible loop for restarting your program. The best loop for restarting your program is actually a Do While loop since it always runs the statement's in the loop once before checking if the expression is true or not.
  17. true

Short Answer:

  1. In your own words describe the difference between a Do and a Do While loop.
  2. If you wanted to create a program that asked for a name on startup, and wouldn't advance until given one, what type of loop would you use and why?

Fill in the blank: Practicing Truth Tables[edit | edit source]

  1. True AND False = _____
  2. False AND NOT False = _____
  3. True OR True = _____
  4. True AND False = _____
  5. False OR NOT True = _____
  6. True AND True = _____
  7. False OR True = _____
  8. False AND False = _____

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.

  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 | edit source]

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 the user’s 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 | edit source]

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 | edit source]

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
  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.

References[edit | edit source]