12 Repetitions and Loops.pptx - Topic 12 Repetition and Loops 1 Repetition in Programs Remember that there are 3 types of program control structures

# 12 Repetitions and Loops.pptx - Topic 12 Repetition and...

• 65

This preview shows page 1 - 17 out of 65 pages.

Topic 12 Repetition and Loops 1 Repetition in Programs Remember that there are 3 types of program control structures: sequence , selection and repetition . Just as the ability to make decisions is an important programming tool, so is the ability to specify repetition of a group of operations. 2 Repetition in Programs Suppose we want a program to add 4 pairs of numbers. Example: 34526 + 23135 = ? 4222 + 29856 = ? 30765 + 45692 = ? 590299 + 87823 = ? 3 Repetition in Programs This flowchart shows how a program can add 2 numbers. Start Stop Read n1, n2 sum ← n1 + n2 Display sum 4 Repetition in Programs Do we extend the flowchartwith the same set of stepsfor the 4 pairs of numbers? Start Stop Read n1, n2 sum ← n1 + n2 5 Repetition in Programs Start Read n1, n2 sum ← n1 + n2 Display sum 1 st pair Read n1, n2 sum ← n1 + n2 Display sum 2 nd pair Read n1, n2 sum ← n1 + n2 Display sum Read n1, n2 sum ← n1 + n2 Display sum Stop 3 rd pair 4 th pair 6 LoopsWhat if we have 100pairs? 7 Loops This flowchart shows the concept of a loop. The loop action or actions form the loop body. One loop iteration is one execution of the loop body. 8 Loops Example – to add many pairs of numbers: Read n1, n2 sum ← n1 + n2 Display sum 9 Loops But this loop never stops. It is called an infinite loop . We want our loop to end when the work is done i.e. we iterate or repeat the loop actions until the work is done. To make sure it ends, we must have a condition that controls the loop. This condition is called a loop control expression . 10 Loops The condition must be tested before or after each iteration to decide whether to repeat the loop one more time or exit/terminate the loop. There are two types of loops depending on when the condition is tested: Pretest loop Post-test loop 11 Loops Pretest loop : In each iteration, the control expression is tested first. If it is true, the loop action(s) are executed; otherwise, the loop terminates. Post-test loop : In each iteration, the loop action(s) are executed. Then the control expression is tested. If it is true, a new iteration is started; otherwise, the loop terminates. 12 Pretest Loop This flowchart shows a pretest loop. loop body – executed while condition is true. loop test 13 Post-Test Loop This flowchart shows a post-test loop. loop body executed while condition is true . loop test 14 Pretest versus Post-Test Loops 15   • • • 