Download presentation
Presentation is loading. Please wait.
Published byNelson Hill Modified over 9 years ago
1
Chapter 5: Repetition and Loop Statements By: Suraya Alias
2
5.1 Repetitions in Program Loop –a control structure that repeats a group of steps in a program 3 loop control statements While, for, do-while Loop body contains the statements to be repeated 1323638
3
Figure 5.1 Flow Diagram of Loop Choice Process 1-3
4
1-4 Loop types 1) Counting loopCan be determines before loop execution, exactly how many loop repetition will be needed to solve the problem While for 2) sentinel- controlled loop Input of a list of data of any length ended by a special value While, for 3) endfile- controlled loop Input of a single list of data of any length from a a data file While, for 4) Input validation loop Repeated interactive input of data value until a a value within the valid range is entered do-while 5) General conditional loop Repeated processing of data until a desired condition is met While, for
5
5.2 Counting loops and the while statement Counter-controlled loop (counting loop) is a loop whose required number of iterations can be determined before loop execution begins Format Set loop control variable = 0 While loop control variable < final value Increase loop control variable by 1
6
The While Statement while (count_emp < 7) (count_emp < 7) is the loop repetition condition, a condition which control the loop repetition The loop is repeated when the condition is true, the loop exited when false count_emp is the loop control variable because it determines whether the loop body is repeated. The loop control variable must be; Initialized, count_emp = 0 Tested, count_emp is tested before the start of each loop repetition Updated, count_emp is updated (value increased by 1) during each iteration
7
Syntax of while statement Syntax : while (loop repetition condition) Statement Example - /* display N star*/ count_star = 0; while (count_star < N) { printf(“*”); count_star = count_star + 1; }
8
Figure 5.2 Program Fragment with a Loop 1-8
9
Figure 5.3 Flowchart for a while Loop 1-9
10
5.3 Computing a Sum or a product in a Loop Accumulator – a variable used to store a value being computed in increments during the execution of a loop total_pay = total_pay + pay; /* add next pay*/ The value of total_pay increases with each loop iteration. To write general loops, the loop repetition condition can be manipulated count_emp < number_emp The number of employees must be scanned into variable number_emp before the while statement executes. We also can use loop to compute the product of a list product = product * item;
11
Figure 5.4 Program to Compute Company Payroll 1- 11
12
Figure 5.4 Program to Compute Company Payroll (cont’d) 1- 12
13
Compound Assignment Operators Statement with simple assignment operator Equivalent statement with compound assignment operator count_emp = count_emp + 1;Count_emp +=1; time = time – 1;time -= 1; total_time = total_time + timetotal_time += time product = product * item;product *= item; n = n * (x + 1);n *= (x + 1);
14
5.4 The For Statement A for statement has 3 loop control component that is initialization, testing and update in one place. for (count_emp = 0; /*initialization*/ count_emp < number_emp; /*loop repetition condition*/ Count_emp +=1) /*update*/ Syntax : for (initialization expression; Loop repetition condition; Update expression) statement
15
Figure 5.5 Using a for Statement in a Counting Loop 1- 15
16
Increment and decrement operators for (counter = 0; counter < limit; ++counter) The side effect of applying the ++ operator is that the value of its operand is incremented by one. The value of the expression in which the ++ is used depends on the position of the operator Prefix increment : j = ++i The value of the expression is the variables value after incrementing Postfix increment : j = i++ The value of the expression is the variables value before incrementing
17
Figure 5.6 Comparison of Prefix and Postfix Increments 1- 17
18
Figure 5.7 Function to Compute Factorial 1- 18
19
Figure 5.8 Displaying a Celsius-to-Fahrenheit Conversion Table 1- 19
20
5.5 Conditional Loops Is used to control the number of time the loop executes/repeats. Such as continue prompting the user for data as long as the response is unreasonable. The loop can be process in a function subprogram, it simplifies the main function.
21
Figure 5.9 Program to Monitor Gasoline Storage Tank 1- 21
22
Figure 5.9 Program to Monitor Gasoline Storage Tank (cont’d) 1- 22
23
Figure 5.9 Program to Monitor Gasoline Storage Tank (cont’d) 1- 23
24
5.6 Loop design Sentinel-Controlled Loops Sentinel value is an end marker that follows the last item in a list of data Sentinel loop 1. Initialize sum to zero 2. Get first score 3. While score is not the sentinel 1. Add score to sum 2. Get next score
25
Figure 5.10 Sentinel-Controlled while Loop 1- 25
26
Sentinel Loop using For printf(“enter first score(or %d to quit) >”, sentinel); for (scanf(“%d”, &score); score !=sentinel; scanf(“%d”, &score)) { sum += score; printf(“Enter next score (%d to quit)>”,sentinel); }
27
Endfile-Controlled Loop & Infinite loops on faulty data Figure 5.11 Batch Version of Sum of Exam Scores Program Figure 5.11 Batch Version of Sum of Exam Scores Program 1- 27
28
5.7 Nested loops Figure 5.12 Program to Process Bald Eagle Sightings for a Year Figure 5.12 Program to Process Bald Eagle Sightings for a Year 1- 28
29
Figure 5.12 Program to Process Bald Eagle Sightings for a Year (cont’d) 1- 29
30
5.8 the do-while statement and Flag-Controlled Loops Syntax : do Statement while (loop repetition condition); Example : Do Status = scanf(“%d”,num); While (status > 0 && (num % 2) !=0); Flag = is a type int variable used to represent whether or not a certain event has occurred. The flag has the value of true(1) and false(0);
31
Figure 5.13 Nested Counting Loop Program 1- 31
32
Figure 5.14 Validating Input Using do-while Statement 1- 32
33
Figure 5.15 Structure Chart for Computing Solar Collecting Area Size 1- 33
34
Figure 5.16 Program to Approximate Solar Collecting Area Size 1- 34
35
Figure 5.16 Program to Approximate Solar Collecting Area Size (cont’d) 1- 35
36
Figure 5.16 Program to Approximate Solar Collecting Area Size (cont’d) 1- 36
37
Figure 5.16 Program to Approximate Solar Collecting Area Size (cont’d) 1- 37
38
5.10 How to debug and test Programs Using debugger programs Using Single step execution or breakpoints Debugging without a debugger Using printf or diagnostic call Loop boundaries = initial and final values of the loop control variable Test by running program using multiple test data
39
New C construct Counting for loop For (num=0; num < 26; ++num) { Square = num * num; Printf(“%5d %5d\n”, num, square); } Counting for loop with negative steps For (volts=20; volts>=-20; volts -=10) { current = volts/resistance; printf(“%5d %8.3f\n”, volts, current); } Sentinel controlled while loop product = 1; printf(“Enter %d to quit\n”, senval); printf(“Enter first number”); scanf(“%d, &dat”); while (dat != senval) { product *=dat; printf(“next number”); scanf(“%d”, &dat);} Endfile controlled while loop sum=0; status = fscanf(infil, “%d”, &n); while (status ==1){ sum += n; status = fscanf(infil, “%d”, &n); }
40
New C construct do-while loop do { Printf(“positive number < 10”); sacnf(“%d”, &num); } while (num = 10); Increment/ decrement Z= ++j * k--; Compound Assignment Ans *= a – b;
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.