Presentation is loading. Please wait.

Presentation is loading. Please wait.

REPETITION CONTROL STRUCTURE

Similar presentations


Presentation on theme: "REPETITION CONTROL STRUCTURE"— Presentation transcript:

1 REPETITION CONTROL STRUCTURE
CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE

2 Contents Introduction 1 for loop 2 while loop 3 do … while loop 4

3 Introduction It is used when a statement or a block of statements need to be executed several times. Programmers use the repetition structures, referred to more simply as a loop, when they need the computer to repeatedly process one or more program instructions until some condition is met, at which time the repetition structures end. Repetition is also known as iteration or loop.

4 Introduction Two types of loop: Pretest loop Posttest loop
Evaluation occurs before the instructions within the loop are processed Instruction may never be processed while statement, for statement Posttest loop Evaluation occurs after the instructions within the loop are processed Instructions will be processed at least once do..while statement

5 Introduction – example
Let say, you want to display “ I love C++” 5 times. I love C++ void main() { cout << “ I love c++!\n”; }

6 Introduction – example
The idea of using a loop… Pseudocode Flow Chart Begin Repeat output “I love C++” End I love C++ QUESTION: HOW DO WE STOP THE LOOP???

7 Introduction – example
Adding a loop control variable Pseudocode Flow Chart Begin counter = 1 Repeat (if counter <= 5) output “I love C++” counter ++ End counter = 1 counter <= 5 T Variable counter is LCV F I love C++ counter ++

8 Introduction – loop control variable
A LCV controls the number of times the statement or the block of statements is being executed. Flow Chart Pseudocode Counter = 1 Begin counter = 1 Repeat (if counter <= 5) output “I love C++” counter ++ End Counter <= 5 T F I love C++ Counter ++

9 Introduction Requirement of a repetition structure Flow Chart
Loop body Initialize LCV Counter = 1 Counter <= 5 T F I love C++ Evaluate LCV (loop condition) Counter ++ Update LCV

10 Introduction Task associated with loop: sum = sum + variable
Counter – to determine number of items. Is done by adding a constant, such as 1 or 2, to the value of a variable. Accumulator – to find totals. Is done by adding a variable to another variable. counter = counter + 1 sum = sum + variable

11 Introduction Indicator – value use to end the loop Indicators
Sentinel control Counter control While(counter<=5) sentinel=999; While(number!=sentinel) Counter control sentinel control

12 The for loop

13 for loop Also called as a counted or indexed for loop
The general form of the for statement is: The initial statement, loop condition, and update statement are called for loop control statements Items in square brackets ([ ]) are optional. for ([initial statement]; loop condition; [update statement]) statement;

14 for loop The for loop executes as follows:
for ([initial statement]; loop condition; [update statement]) statement; The for loop executes as follows: 1. The initial statement executes. 2. The loop condition is evaluated. If the loop condition evaluates to true i. Execute the for loop statement. ii. Execute the update statement (the third expression in the parentheses). Repeat Step 2 until the loop condition evaluates to false. The initial statement usually initializes a variable. In C++, for is a reserved word.

15 for loop – Example 1 Example : Displaying the numbers 1 through 3
initialization condition update for (int count = 1; count <= 3; count = count + 1) cout << count << endl; Result: 1 2 3

16 for loop – Example 1 Using for loop to display ‘Welcome to C++’.
Pseudocode: Start For( set i to 1; i less than or equal to 3; add 1 to i) display “welcome to C++” Endfor End

17 Display “welcome to C++”
for loop – Example 1 Start Flowchart i = 0 i <= 10 F End T Display “welcome to C++” i ++

18 for loop – Example 2 Example: to create a program to display backward the first 10 non negative number.

19 for loop – Exercises Exercise 1: create a program that display the first 10 positive odd integers.

20 for loop – Exercises Exercise 1 - answer

21 for loop – Exercises Exercise 2: how many time the following loop processed? Answer: for (int count = 6; count < 6; count = count + 1) cout << count << endl;

22 for loop – Exercises Exercise 3: how many time the following loop processed? Answer: for (int count = 4; count <= 10; count = count + 2) cout << count << endl;

23 for loop – Example 3 Example: to calculate and display total of 3 numbers

24 for loop – Example 3 Pseudocode: Start Initialize total = 0
For(set counter to 1; counter less than or equal to 3; add 1 to counter) input number total = total + number Endfor Display total End

25 for loop – Example 3 Flowchart Start counter=1, total = 0, F
for counter <= 3 F Output total T End Input number total = total + number counter = counter + 1

26 for loop – Example 3 C++ program segment total = 0;
for (int count = 1; count <= 3; count = count + 1) { cin>>number; total = total + number; } cout << “total:” <<total<<endl;

27 for loop – Exercises Exercise 4: Suppose j, sum, and num are int variables, and the input values are 26, 34, 61, 4, and -1. What is the output of the code below? cout << "Enter a number : "; cin >> num; for (j = 1; j <= 4; j++) { sum = sum + num; } cout << sum << endl;

28 for loop – Exercises Exercise 4: answer

29 for loop A semicolon at the end of the for statement (just before the body of the loop) is a semantic error. In this case, the action of the for loop is empty. In the for statement, if the loop condition is omitted, it is assumed to be true. In a for statement, you can omit all three statements—initial statement, loop condition, and update statement. The following is a legal for loop:

30 for loop for (;;) cout << "Hello" << endl; This is an infinite loop, continuously printing the word Hello

31 The while loop

32 while loop Repeat or loop as long as the condition is true.
The general form of the while statement is: while is a reserved word. Statement can be simple or compound while (expression) { statement; }

33 while loop while (expression) { statement; } Expression acts as a decision maker and is usually a logical expression Statement is called the body of the loop The parentheses are part of the syntax

34 while loop Expression provides an entry condition
while (expression) { statement; } Expression provides an entry condition statement executes if the expression initially evaluates to true loop condition is then reevaluated statement continues to execute until the expression is no longer true

35 while loop Infinite loop continues to execute endlessly
can be avoided by including statements in the loop body that assure exit condition will eventually be false

36 while loop The general form of while loop flowchart:

37 while loop Example: to display the first five positive integers which increment by five.

38 while loop Pseudocode: Begin Initialize i to 0
While i is less than or equal to 20 Display i add 5 to I (update) End while End

39 Go back and reevaluate the expression
while loop Start i = 0 Enter the while statement Expression evaluates to zero i <= 20 End False condition Expression evaluates to a nonzero number True condition Loop Display i i = i + 5 Go back and reevaluate the expression

40 while loop Example C++ program segment: i = 0; while ( i <= 20) {
2) A starting point / Initialization of the LCV 1) Loop Control Variable (LCV) i = 0; while ( i <= 20) { cout << i << “ “; i = i + 5; } 3) Testing the loop repetition condition 4) Updating the LCV

41 while loop Various form of while loops: Counter controlled
Sentinel controlled Flag controlled

42 while loop – counter control
If you know exactly how many pieces of data need to be read, the while loop becomes a counter-controlled loop. General syntax:

43 while loop – counter control
Counter controlled while loop includes the following: Counter A numeric variable used for counting something Accumulator Numeric variable used for accumulating something Initializing Assign a beginning value to the counter or accumulator; typically 0 Updating Also called incrementing, means adding a number to the values stored in the counter or accumulator

44 while loop – counter control
Example #include <iostream> #include <conio> int main() { int count; count = 1; while (count <= 10) cout << count << endl; count++; } getch(); return 0; initializing updating

45 while loop – counter control
Problem: Create a program that displays the word ‘Hello’ on the screen 10 times. Solution: Psedocode Begin Initialize lcv to 0 While lcv is less than 10 Display “Hello” Update lcv End while End

46 while loop – counter control
Flowchart Begin Initialize counter = 0 counter < 10 Hello update counter T F End

47 while loop – counter control
Program and output int main() { int count; count = 0; while (count < 10) cout << "Hello" << endl; count++; } getch(); return 0;

48 while loop – counter control
Exercise: Write a C++ statement associated to the following flowchart. Begin Initialize counter = 10 counter < 100 Display counter Multiplied by 2 Add 10 to counter T F End

49 while loop – counter control
Program and output int main() { int count; count = 10; while (count < 100) cout << count * 2 << endl; count += 10; } getch(); return 0;

50 while loop – sentinel control
A sentinel-controlled while loop uses a special value called sentinel to control the loop. Sentinel value is a special value that indicates the end of a set of data or of a process Sentinel variable is tested in the condition and loop ends when sentinel is encountered

51 while loop – sentinel control
General syntax :

52 while loop – sentinel control
Example #include <iostream> #include <conio> int main() { char answer; cout << "Do you want to quit (Y - yes, N - no) : "; cin >> answer; while (answer != 'Y') cout << "Welcome to the program." << endl; cout << "Do you want to quit (Y - Yes, N - No) : "; } cout << "Bye."; getch(); return 0; Sentinel value

53 while loop – sentinel control
Output screen

54 while loop – sentinel control
Exercise: to create a program that process the loop as long as user enter an even number

55 while loop – sentinel control
Solution Flowchart Begin End number % 2 == 0 Get another number F Prompt for a number Get T

56 while loop – sentinel control
Program int main() { int number; cout << "Enter a number : "; cin >> number; while (number % 2 == 0) cout << "Enter the next number : "; } cout <<"You have entered an odd number to terminate” <<“the program."; getch(); return 0;

57 while loop – sentinel control
Output

58 while loop – flag control
A flag-controlled while loop uses a bool variable to control the loop The flag-controlled while loop takes the form:

59 while loop – flag control
Example void main() { bool found = false; char continue; while (!found) cout << " Program continued..still want to continue" << " the loop? Press Y for yes, N for No"<< endl; cin>>continue; if(continue == ‘Y’) found = false; else found = true; } cout << "Program terminated"; getch();

60 The do … while loop

61 do … while loop The general form of a do...while statement is:
The statement executes first, and then the expression is evaluated. If the expression evaluates to true, the statement executes again As long as the expression in a do...while statement is true, the statement executes do statement while (expression);

62 do … while loop General form of flowchart:

63 do … while loop To avoid an infinite loop, the loop body must contain a statement that makes the expression false The statement can be simple or compound. If compound, it must be in braces do...while loop has an exit condition and always iterates at least once (unlike for and while)

64 do … while loop Example: to display the first five positive integers which increment by five.

65 do … while loop Pseudocode: Begin Initialize i to 0 do Display i
add 5 to I (update) While i is less than or equal to 20 End

66 Go back and reevaluate the expression
do … while loop Start Flowchart i = 0 Enter do statement Expression evaluates to zero Display i End False condition True condition Expression evaluates to a nonzero number Loop i = i + 5 i <= 20 Go back and reevaluate the expression

67 do … while loop C++ program segment i = 0; do {
cout << i << “ “; i = i + 5; } while ( i <= 20)

68 do … while loop Exercise 1 a. The while loop produces nothing.
b. The do..while loop outputs the number 11 and also changes the value of i to 16.

69 do … while loop Exercise 2 – determine the output of the following program int x = 20; do { cout << x << endl; x = x – 4; } while (x > 10)

70 do … while loop Exercise 3 – determine the output of the following program int x = 1; do { cout << x << endl; x = x + 1; } while (x < 5)

71 do … while loop Exercise 4 – determine the output of the following program int total = 1; do { cout << total << endl; total = total + 2; } while (total >=3)

72 do … while loop Answer: INFINITE LOOP!

73 Nested Control Structures

74 Nested loop In many situations, it is very convenient to have a loop contained within another loop. Such loops are called nested loops. For each single trip, through the outer loop, the inner loop runs through its entire sequence. Each time counter i increases by 1, the inner loop executes completely.

75 Nested loop Example of C++ program segment for (i = 0; i <= 5; i++)
{ cout << "\n i is now " << i << endl; for (j = 1; j <= 4; j++) cout << " j = " << j ; }

76 Nested loop How it works… i is now 0 Outer loop
j = 1 j = 2 j = 3 j = 4 i is now 1 i is now 2 i is now 3 i is now 4 i is now 5 Inner loop

77 Nested loop ** *** **** *****
Suppose we want to create the following pattern. In the first line, we want to print one star, in the second line two stars and so on. * ** *** **** *****

78 Nested loop Since five lines are to be printed, we start with the following for statement. for (i = 1; i <= 5 ; i++) The value of i in the first iteration is 1, in the second iteration it is 2, and so on Can use the value of i as limit condition in another for loop nested within this loop to control the number of starts in a line.

79 Nested loop The syntax for (i = 1; i <= 5 ; i++) {
for (j = 1; j <= i; j++) cout << "*"; cout << endl; }

80 Nested loop What pattern does the code produce if we replace the first for statement with the following? for (i = 5; i >= 1; i--) Answer: ***** **** *** ** *

81 The jump statements

82 break Causes an exit from loop or switch statement void main() {
int x; for (x = 1; x<=10; x++) if (x == 5) break; cout<< x <<“”; } cout<< “ loop terminated at x:”<<x<<endl; loop terminated at x: 5 Press any key to continue

83 continue Skips the remaining statements in the loop and proceed with the next loop void main() { int x; for (x = 1; x<=10; x++) if (x == 5) a=x; continue; } cout<< x <<“”; cout<< “ the number”<<a<<endl; cout<< “ is not printed”<<endl; the number 5 is not printed Press any key to continue

84 Thank You !


Download ppt "REPETITION CONTROL STRUCTURE"

Similar presentations


Ads by Google