Download presentation
Presentation is loading. Please wait.
Published byLionel Hodges Modified over 6 years ago
1
EGR 2261 Unit 5 Control Structures II: Repetition
Read Malik, Chapter 5. Homework #5 and Lab #5 due in two weeks. Exam #1 next week. -Handouts: Quiz 4, Unit 5 practice sheets.. -Preview Exam #1.
2
Review: Flow of Execution
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
3
Why Is Repetition Useful?
Repetition can result in more efficient programs. It lets you process many values using a small number of lines of code. See the following two slides for examples of two approaches to finding the sum of five numbers. C++ Programming: From Problem Analysis to Program Design, Seventh Edition
4
Inefficient Way of Adding Five Numbers
Demo using week05InefficientAdd2.cpp.
5
Efficient Way of Adding Five Numbers
Demo using week05EfficientAdd.cpp.
6
Three Kinds of Loops
7
while Loop Syntax of the while statement:
statement can be simple or compound. expression acts as a decision maker and is usually a logical expression, such as i < 5. statement is called the body of the loop. The parentheses are part of the syntax. C++ Programming: From Problem Analysis to Program Design, Seventh Edition
8
while Loop (cont’d.) Demo using week05Example5_1.cpp
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
9
Single-Stepping Instead of using Ctrl+F5 to run a program at full speed, you can use F10 (or Debug > Step Over) to single-step a program. This executes the program one statement at a time, and lets you examine the effect of each statement before going on to the next one. It's a powerful debugging technique for any program, particularly for programs that contain loops. To quit single-stepping, press Shift+F5 (or Debug > Stop Debugging). Demo with previous program, with Visual Studio resized so that the console window is also visible.
10
Terminology: Loop Control Variable, Infinite Loop
The variable i in Example 5-1 is called the loop control variable. An infinite loop ( or “forever loop”) continues to execute endlessly. Infinite loops are generally undesirable. They can be avoided by including statements in the loop body that assure that expression is eventually false. Demo infinite loop by removing i=i+5 from previous program. To break, just close console window. C++ Programming: From Problem Analysis to Program Design, Seventh Edition
11
while Loop (cont’d.) Demo using previous program.
Then do practice question 1. C++ Programming: From Problem Analysis to Program Design, Seventh Edition
12
Four Common Ways of Using while Loops
There are many ways to use while loops. The following slides discuss four common ways. These differ mainly in the value that is used for the loop control variable: Counter-controlled while loops Sentinel-controlled while loops Flag-controlled while loops EOF-controlled while loops (“EOF” stands for “End-Of-File”)
13
Case 1: Counter-Controlled while Loops
In a counter-controlled while loop a numeric variable is increased or decreased each time through the loop, and the loop continues executing until this variable’s value rises above or falls below a certain limit. Do practice question 2. C++ Programming: From Problem Analysis to Program Design, Seventh Edition
14
Case 2: Sentinel-Controlled while Loops
In a sentinel-controlled while loop, the condition checks to see whether a variable is equal to a special value called the sentinel value. Do practice question 3. C++ Programming: From Problem Analysis to Program Design, Seventh Edition
15
Example 5-5: Telephone Digits
The textbook’s Example 5-5 (p. 278) provides an example of a sentinel-controlled loop. The program converts uppercase letters to their corresponding telephone digit. It loops until the users enters ‘#’ to indicate that she wants to quit the program. Run week05Example5_5.cpp C++ Programming: From Problem Analysis to Program Design, Seventh Edition
16
Case 3: Flag-Controlled while Loops
Flag-controlled while loop: uses a bool variable to control the loop. Do practice question 4. C++ Programming: From Problem Analysis to Program Design, Seventh Edition
17
Example 5-6: Number Guessing Game
The textbook’s Example 5-6 (p. 282) implements a number guessing game using a flag-controlled while loop. It also uses the function rand of the header file <cstdlib> to generate a random number. rand() returns an int value between 0 and 32767 To convert to an integer >= 0 and < 100: rand() % 100 Run week05Example5_6.cpp C++ Programming: From Problem Analysis to Program Design, Seventh Edition
18
Case 4: EOF-Controlled while Loops
EOF stands for end-of-file. An EOF-controlled while loop reads data from a disk file until it encounters a special end-of-file character that is automatically included at the end of every file on a disk. C++ Programming: From Problem Analysis to Program Design, Seventh Edition
19
eof Function The eof function looks in an input stream for the end-of-file character. Syntax for the eof function: The expression above is false as long as we haven’t reached the end-of-file character; otherwise the expression is true. inputFile.eof(); C++ Programming: From Problem Analysis to Program Design, Seventh Edition
20
Example: EOF-Controlled While Loop
Demo using week05EOFLoop.cpp.
21
Another Way to Do an EOF-Controlled While Loop
You’ll often see the following simpler way of reading from an input file until we hit the end of the file. Instead of saying while (!infile.eof()) you can simply say while (infile) This expression is true until we hit the end of the file; then it becomes false.
22
Example: Another Way to Do an EOF-Controlled While Loop
Demo using week05EOFLoop_2.cpp.
23
More on Expressions in while Statements
The expression in a while statement can be complex. Example: int i = 0; while (i < 20 && !infile.eof()) { . . . i++; } C++ Programming: From Problem Analysis to Program Design, Seventh Edition
24
Three Kinds of Loops
25
Review: Four Common Ways of Using while Loops
We’ve looked at four common ways of using while loops: Counter-controlled while loops Sentinel-controlled while loops Flag-controlled while loops EOF-controlled while loops For loops provide a good alternative for the first of these, but not for the other three.
26
for Loop Example: of a counter-controlled while loop:
As an alternative, many people prefer to use a for loop: int i = 0; while (i < 5) { cout << i << " "; i++; } Note that the three pieces dealing with the loop control variable are all brought into one place. for (int i = 0; i < 5; i++) { cout << i << " "; } C++ Programming: From Problem Analysis to Program Design, Seventh Edition
27
for Loop (cont’d.) Syntax:
The initial statement executes only once, when execution of the for loop begins. The loop condition is checked at the beginning of each repetition. If it is true, the loop is repeated. If it is false, control passes to the first statement after the end of the loop. The update statement executes at the end of each repetition. C++ Programming: From Problem Analysis to Program Design, Seventh Edition
28
for Loop (cont’d.) Run week05Example5_9.cpp Do practice question 5.
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
29
for Loop (cont’d.) The following is a legal (but infinite) for loop:
cout << "Hello" << endl; The following is also legal, but probably not what the programmer wanted: C++ Programming: From Problem Analysis to Program Design, Seventh Edition
30
for Loop (cont’d.) You can count backward using a for loop. Example:
You can also increase or decrease the loop control variable by more than 1. Example: Do as Practice Question 6. C++ Programming: From Problem Analysis to Program Design, Seventh Edition
31
Three Kinds of Loops
32
do…while Loop Syntax of a do...while loop:
The statement executes first, and then the expression is evaluated. The statement can be simple or compound. The statement always executes at least once. As long as expression is true, loop continues. C++ Programming: From Problem Analysis to Program Design, Seventh Edition
33
do…while Loop (cont’d.)
Do practice question 7. C++ Programming: From Problem Analysis to Program Design, Seventh Edition
34
Three Kinds of Loops
35
Choosing the Right Kind of Loop
All three loops have their place in C++. If you can determine in advance the number of repetitions needed, the for loop is the best choice. If you cannot determine in advance the number of repetitions needed, and it could be zero, use a while loop. If you cannot determine in advance the number of repetitions needed, and it is at least one, use a do...while loop. C++ Programming: From Problem Analysis to Program Design, Seventh Edition
36
break and continue Statements
The break and continue statements alter the normal flow of execution in a loop. Most loops do not contain break or continue statements. These are special-case statements that you probably will not use very often. But they’re handy when you need them. You can use them in any kind of loop-- while, for, or do…while. C++ Programming: From Problem Analysis to Program Design, Seventh Edition
37
The break Statement The break statement is used to exit early from a loop. After break executes, the program continues with the first statement after the loop. Recall from Unit 4 that break is also used to skip the remainder of a switch structure. So whether you use it in a loop or in a switch structure, break is a way of saying “Get me out of here!” C++ Programming: From Problem Analysis to Program Design, Seventh Edition
38
We’ll bail out of the loop to avoid dividing by 0.
Example: Using break in a while Loop We’ll bail out of the loop to avoid dividing by 0. Run week05LoopWithBreak.cpp, and single-step it to show effect of break. Then do practice question 8.
39
The continue Statement
When continue is executed in a loop, it skips the remaining statements in the loop and proceeds with the loop’s next iteration. So whereas break is a way of saying “Get me out of here,” continue is a way of saying “Let’s skip this one and try again.” C++ Programming: From Problem Analysis to Program Design, Seventh Edition
40
Example: Using continue in a while Loop
The only difference from the previous program is that we’ve replaced break with continue. Run week05LoopWithContinue.cpp, and single-step it to show effect of continue. Then do practice question 9.
41
Debugging Loops Loops are harder to debug than sequence and selection structures. While debugging, insert temporary cout statements in your loop so that you can see how the values of variables are changing as the loop repeats—or use single-stepping. The most common error associated with loops is the off-by-one error (doing a counted loop one too many times or one too few times). C++ Programming: From Problem Analysis to Program Design, Seventh Edition
42
A New Debugging Tool: Breakpoints
Previously we’ve seen two ways to run a program: At full speed using Debug >> Start Without Debugging (Ctrl+F5) One step at a time using Debug >> Step Over (F10) Suppose you have a long program. Is there a way to run the first part of it at full speed and then switch over at some point into single-step mode? Yes! You can set a breakpoint in your program and then run it using Debug >> Start Debugging (F5). Note: Don’t confuse breakpoints with the break statement discussed earlier. They’re unrelated.
43
Setting a Breakpoint To set a breakpoint on a statement, click in the vertical gray bar to the statement’s left (or click on the statement and and select Debug >> Toggle Breakpoint (F9)). A red circle will appear to the left. Demo using previous program by placing a breakpoint on the statement that calculates speed.
44
Using a Breakpoint After you’ve set one or more breakpoints, select Debug >> Start Debugging (F5) to run the program. Don’t press Ctrl-F5, or it will run right through the breakpoint. The program runs full-speed up to the statement, and then pauses so that you can use F10 to single-step. To resume full-speed execution, select Debug >> Continue (F5). Or to abort execution, press Shift+F5 (or Debug > Stop Debugging, or press the red rectangle on the toolbar.)
45
Nested Loops To create the following pattern:
******** we can use the following code: for (int i = 1; i <= 5 ; i++) { for (int j = 1; j <= 8; j++) cout << "*"; cout << endl; } Outer loop. Inner loop. C++ Programming: From Problem Analysis to Program Design, Seventh Edition
46
The only difference from the previous program.
Nested Loops (Cont’d.) To create the following pattern: * ** *** **** ***** we can use the following code: for (int i = 1; i <= 5 ; i++) { for (int j = 1; j <= i; j++) cout << "*"; cout << endl; } The only difference from the previous program. Outer loop. Do practice question 10. Inner loop. C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.