Chapter 5: Control Structures II (Repetition)

Similar documents
Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

Why Is Repetition Needed?

C++ Programming: From Problem Analysis to Program Design, Third Edition

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

REPETITION CONTROL STRUCTURE LOGO

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

LECTURE 5 Control Structures Part 2

Programming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester

Chapter 5: Loops and Files

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

Increment and the While. Class 15

Lecture 7 Tao Wang 1

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad

Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept.

Repetition Structures

Introduction. C provides two styles of flow control:

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

Control Structures of C++ Programming (2)

Looping. Arizona State University 1

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

CSc Introduc/on to Compu/ng. Lecture 8 Edgardo Molina Fall 2011 City College of New York

In this chapter you will learn:

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

SFU CMPT Topic: Control Statements

Control Structures II. Repetition (Loops)

C++ PROGRAMMING SKILLS Part 2 Programming Structures

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

Add Subtract Multiply Divide

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 4: Repetition Control Structure

Loops / Repetition Statements

Chapter 3. More Flow of Control

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Loops and Files. of do-while loop

Information Science 1

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Loops (while and for)

Unit 7. 'while' Loops

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Name Section: M/W T/TH Number Definition Matching (8 Points)

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition)

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

C++ Final Exam 2017/2018

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Chapter 4 C Program Control

Structured Programming. Flowchart Symbols. Structured Programming. Selection. Sequence. Control Structures ELEC 330 1

Programming Language. Functions. Eng. Anis Nazer First Semester

Lecture 7: General Loops (Chapter 7)

Information Science 1

Repetition and Loop Statements Chapter 5

Quiz Determine the output of the following program:

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

To become familiar with array manipulation, searching, and sorting.

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

8. Control statements

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS240 BRANCHING STATEMENTS

Chapter 2 - Control Structures

C++ Programming: From Problem Analysis to Program Design, Third Edition

Chapter 2 - Control Structures

ECE 122. Engineering Problem Solving with Java

Chapter 2 - Control Structures

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Control Statements. Musa M. Ameen Computer Engineering Dept.

Chapter 4: Control structures. Repetition

Chapter 4: Control Structures I (Selection)

Name Section: M/W T/TH Number Definition Matching (6 Points)

causing a set of statements (the body) to be executed repeatedly. C++ provides three control structures to support iteration (or looping).

The following expression causes a divide by zero error:

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.5. for loop and do-while loop

Programming for Engineers Iteration

Computer Programming I - Unit 5 Lecture page 1 of 14

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

causing a set of statements (the body) to be executed repeatedly. C++ provides three control structures to support iteration (or looping).

CS110D: PROGRAMMING LANGUAGE I

STUDENT LESSON A12 Iterations

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Repetition, Looping CS101

Transcription:

Chapter 5: Control Structures II (Repetition) 1

Objectives Learn about repetition (looping) control structures Explore how to construct and use count-controlled, sentinel-controlled, flag-controlled, and EOF-controlled repetition structures Examine break and continue statements Discover how to form and use nested control structures Learn how to avoid bugs by avoiding patches Learn how to debug loops 2

Why Is Repetition Needed? Repetition allows you to efficiently use variables Can input, add, and average multiple numbers using a limited number of variables For example, to add five numbers: Declare a variable for each number, input the numbers and add the variables together Create a loop that reads a number into a variable and adds it to a variable that contains the sum of the numbers 3

Read and Add Numbers 2 Numbers int Sum; int N1; cin >> N1; int N2; cin >> N2; Sum = N1 + N2; cout << Sum; START INPUT N1 INPUT N2 COMPUTE Sum=N1+N2; OUPUT Sum STOP 4

Read and Add Numbers 3 Numbers int Sum; int N1; cin >> N1; int N2; cin >> N2; int N3; cin >> N3; Sum = N1 + N2 + N3; cout << Sum; START INPUT N1 INPUT N2 INPUT N3 COMPUTE Sum=N1+N2+N3; OUPUT Sum STOP 5

Read and Add Numbers 3 Numbers int Sum; int N1; cin >> N1; int N2; cin >> N2; int N3; cin >> N3; Sum = N1 + N2 + N3; cout << Sum; 3 Numbers Sum so far int Sum=0; int N1; cin >> N1; Sum = Sum + N1; int N2; cin >> N2; Sum = Sum + N2; int N3; cin >> N3; Sum = Sum + N3; cout << Sum; N1 N2 N3 6

Read and Add Numbers int Sum=0; int N1; cin >> N1; Sum = Sum + N1; int N2; cin >> N2; Sum = Sum + N2; int N3; cin >> N3; Sum = Sum + N3; cout << Sum; N1 N2 N3 int Sum=0; int N; cin >> N; Sum = Sum + N; cout << Sum; REPEAT 3 TIMES 7

Read and Add Numbers int Sum=0; int Sum=0; int N; cin >> N; Sum = Sum + N; REPEAT 3 TIMES int N; cin >> N; Sum = Sum + N; REPEAT 1000 TIMES cout << Sum; cout << Sum; 8

while Looping (Repetition) Structure The general form of the while statement is: while ( Expression ) Statement; while is a reserved word Statement can be simple or compound 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 9

whilelooping (Repetition) Structure false Expression true while ( Expression ) Statement; Statement Infinite loop: continues to execute endlessly Avoided by including statements in loop body that assure exit condition is eventually false 10

whilelooping (Repetition) Structure i=0; i=25; while (i<=20) while (i<=20) { { cout << i << ; cout << i << ; i=i+5; i=i+5; } } cout << \n ; cout << \n ; Sample run: Sample run: 0 5 10 15 20 5 times 0 times 11

whilelooping (Repetition) Structure i=0; i=0; while (i<=20) while (i>=-20) { { cout << i << ; cout << i << ; i=i+5; i=i+5; } } cout << \n ; cout << \n ; Sample run: Sample run: 0 5 10 15 20 _ 5 times INFINITE 12

whilelooping (Repetition) Structure i=0; while (i<=20) { cout << i << ; i=i+5; } cout << \n ; Sample run: 0 5 10 15 20 5 times i=0; while (i<=20); { } cout << i << ; i=i+5; cout << \n ; Sample run: _ INFINITE times 13

whilelooping (Repetition) Structure i=0; while (i<=20) { cout << i << ; i=i+5; } cout << \n ; Sample run: 0 5 10 15 20 5 times i=0; while (i<20) { } cout << i << ; i=i+5; cout << \n ; Sample run: Random number or INFINITE 14

whilelooping (Repetition) Structure i=0; while (i<=20) { } cout << i << ; i=i+5; cout << \n ; Sample run: 0 5 10 15 20 i=0; while (i<20) { } cout << i << ; i=i+5; cout << \n ; Sample run: 0 0 0 0 0 0 0 0 0. 5 times INFINITE 15

Case 1: Counter-Controlled while Loops If you know exactly how many pieces of data need to be read //initialize the counter counter = 0; //test the counter while (counter < N) { //loop statements Statements; //update the counter counter++; } 16

Counter-Controlled while Loops counter = 0 false counter < N true Statement counter=counter +1 counter = 0; while ( counter < N) { Statement; counter++; } 17

Read and Add Numbers int Sum=0; int N; cin >> N; Sum = Sum + N; cout << Sum; REPEAT 5 TIMES int Sum=0; int counter=0; while (counter<5) { } int N; cin >> N; Sum = Sum + N; counter++; cout << Sum; REPEAT 5 TIMES 18

Example: Sum of N Numbers 19

Case 2: Sentinel-Controlled while Loops Sentinel variable is tested in the condition Loop ends when sentinel is encountered //initialize the loop control variable cin >> variable; //test the loop control variable while (variable!= SENTINEL) { //loop statements Statements; //update the loop control variable cin >> variable; } 20

Sentinel-Controlled while Loops false INPUT variable variable!= SENTINEL true Statement INPUT variable cin >> variable; while ( variable!= SENTINEL) { Statement; cin >> variable; } 21

Example: Sentinel-Controlled Sum 22

Example: Letter to Telephone Digits 23

Case 3: Flag-Controlled while Loops A flag-controlled whileloop uses a bool variable to control the loop //initialize the loop control variable found = false; //test the loop control variable while (!found) { //loop statements Statements; //update the loop control variable if (expression) found = true; } 24

Flag-Controlled while Loops false found=false!found false true Statement expression true found=false; while (!found) { Statement; if (expression) found=true; } found=true 25

rand Function Generate a random int value between 0 and 32767 In header file cstdlib To convert it to an integer greater than or equal to 0 and less than 100: rand() % 100 26

Example: Number Guessing Game 27

Case 4: EOF-Controlled while Loops Use an EOF (End Of File)-controlled whileloop to read from an input stream (file) as long as there is something in that stream //initialize the loop control variable InputStream >> variable; //test the loop control variable while (InputStream) { //loop statements Statements; //update the loop control variable InputStream >> variable; } 28

EOF(End of File)-Controlled while Loops false INPUT variable InputStream true Statement cin >> variable; while (InputStream) { Statement; cin >> variable; } INPUT variable 29

eof Function The function eof can determine the end of file status Is true when you read beyond the end of the file eof is a member of data type istream The syntax for the function eof is: istreamvar.eof() where istreamvar is an input stream variable, such as cin or a input file variable 30

Example: Grades First Name Last Name TestScore Letter Grade AVERAGE LetterGrade= A if 90<TestScore B if 80<TestScore<90 C if 70<TestScore<80 D if 60<TestScore<70 F if TestScore<60 For each student ClassAverage= = "# " For the class 31

Example: Grades Flowchart START Sum=0 NumberStudents=0 INPUT FirstName, LastName, AverageTestScore NO ClassAverage = Sum/NumberStudents OUTPUT ClassAverage InputFile YES Calculate LetterGrade Sum = Sum + TestScore OUTPUT Name + LetterGrade STOP NumberStudents = NumberStudents+1 INPUT FirstName, LastName, AverageTestScore 32

Example: Grades 33

More on Expressions in while Statements The expression in a while statement can be complex noofguesses=0; while ((noofguesses < 5) && (!isguessed)) { } cout << "Enter an integer greater than or equal to 0 and less than 100: "; cin >> guess; cout << endl; noofguesses++; 34

Programming Example: Fibonacci Number Consider the following sequence of numbers: 1, 1, 2, 3, 5, 8, 13, 21, 34,... Given the first two numbers of the sequence (say, a 1 and a 2 ) nth number a n, n >= 3, of this sequence is given by: a n = a n-1 + a n-2 35

Programming Example: Fibonacci Number Fibonacci sequence nth Fibonacci number a 2 = 1 a 1 = 1 Determine the nth number, a n, n >= 3 a1 a2 a3 a4 a5 + 36

Programming Example: Fibonacci Number Input: first two Fibonacci numbers the desired Fibonacci number n Output: nth Fibonacci number 37

Programming Example: Fibonacci Number Problem Analysis and Algorithm Design: 1. Get the first two Fibonacci numbers 2. Get the desired Fibonacci number Get the position, n, of the Fibonacci number in the sequence 3. Calculate the next Fibonacci number By adding the previous two elements of the Fibonacci sequence 4. Repeat Step 3 until the nth Fibonacci number is found 5. Output the nth Fibonacci number 38

Programming Example: Fibonacci Number Variables 39

Programming Example: Fibonacci Number Main Algorithm: 1. Prompt the user for the first two numbers that is, previous1 and previous2 2. Read (input) the first two numbers into previous1 and previous2 3. Output the first two Fibonacci numbers 4. Prompt the user for the position of the desired Fibonacci number 5. Read the position of the desired Fibonacci number into nthfibonacci 40

Programming Example: Fibonacci Number 6. a. if (nthfibonacci == 1) The desired Fibonacci number is the first Fibonacci number. Copy the value of previous1 into current b. else if (nthfibonacci == 2) The desired Fibonacci number is the second Fibonacci number. Copy the value of previous2 into current. c. else calculate the desired Fibonacci number as follows: Initialize counter to 3 to keep track of the calculated Fibonacci numbers. 41

Programming Example: Fibonacci Number Calculate the next Fibonacci number, as follows: current = previous2 + previous1; Assign the value of previous2 to previous1 Assign the value of current to previous2 Increment counter Repeat until Fibonacci number is calculated + previous2 previous1 current 7. Output the nth Fibonacci number, which is current 42

Programming Example: Fibonacci Number 43

Programming Example: Fibonacci Number 44

for Looping (Repetition) Structure The general form of the for statement is: for( InitialStatement; LoopCondition; UpdateStatement ) Statement; The InitialStatement, LoopCondition, and UpdateStatement are called for loop control statements InitialStatement usually initializes a variable (called the forloop control, or forindexed, variable) In C++, for is a reserved word 45

forlooping (Repetition) Structure for( InitialStatement; LoopCondition; UpdateStatement ) Statement; InitialStatement false LoopCondition true Statement UpdateStatement 46

forlooping (Repetition) Structure for (i=0; i<10; i++) cout << i << ; cout << endl; Sample output: 0 1 2 3 4 5 6 7 8 9 47

forlooping (Repetition) Structure for loop for (i=0; i<10; i++) cout << i << ; cout << endl; while loop i=0; while (i<10) { cout << i << ; i++; } cout << endl; 48

forlooping (Repetition) Structure for(i=0; i<10; i++) cout << Hello ; cout << * ; simple statement for(i=0; i<10; i++) { } cout << Hello ; cout << * ; compound statement 49

forlooping (Repetition) Structure for(i=0; i<10; i++) { cout << Hello ; cout << * ; } for(i=0; i<10; i++); { cout << Hello ; cout << * ; } 10 times 1 time 50

forlooping (Repetition) Structure The following is a legal for loop: for (;;) cout << "Hello\n ; The following is a legal while loop: while (1) cout << "Hello\n ; Both loops are legal, but not semantically correct. They are infinite loops (never end). 51

forlooping (Repetition) Structure C++ allows you to use fractional values for loop control variables of the double type Results may differ. Avoid using them. An semicolon before the body of the loop will terminate it. for (i=0;i<5;i++); cout << *" << endl; If the initial statement, loop condition, or update statement are omitted (empty) they are assumed to be true and the loop is an infinite loop. for (;;) cout << *" << endl; 52

forlooping (Repetition) Structure Not necessarily in increasing order you can decrement the loop control variable for (i=10; i>0; i--) cout << i << ; cout << endl; Sample output: 10 9 8 7 6 5 4 3 2 1 for (i=10; i>=1; i--) cout << i << ; cout << endl; 53

forlooping (Repetition) Structure Not necessarily consecutive values for the loop control variable for (i=1; i<=10; i=i+2) cout << i << ; cout << endl; for (i=2; i<=10; i=i+2) cout << i << ; cout << endl; Sample output: 1 3 5 7 9 Sample output: 2 4 6 8 10 54

Example: Fibonacci Number 55

do while Looping (Repetition) Structure General form of a do...while: do Statement; while ( Expression ); The statement executes first, and then the expression is evaluated To avoid an infinite loop, body must contain a statement that makes the expression false The statement can be simple or compound Loop always iterates at least once 56

do whilelooping (Repetition) Structure Statement do Statement; while ( Expression ); false Expression true 57

whilelooping (Repetition) Structure i=0; do { cout << i << ; i=i+5; } while (i<=20); cout << \n ; Sample run: 0 5 10 15 20 i=25; do { cout << i << ; i=i+5; } while (i<=20); cout << \n ; Sample run: 0 5 times 1 times 58

whilelooping (Repetition) Structure i=25; do { cout << i << ; i=i+5; } while (i<=20); cout << \n ; Sample run: 0 i=25; while (i<=20) { cout << i << ; i=i+5; } cout << \n ; Sample run: 1 times 0 times 59

Choosing the Right Looping Structure All three loops have their place in C++ If you know or can determine in advance the number of repetitions needed, the forloop is the correct choice If you do not know and cannot determine in advance the number of repetitions needed, and it could be zero, use a whileloop If you do not know and cannot determine in advance the number of repetitions needed, and it is at least one, use a do...whileloop 60

break and continue Statements break and continue alter the flow of control break statement is used for two purposes: To exit early from a loop Can eliminate the use of certain (flag) variables To skip the remainder of the switch structure After the break statement executes, the program continues with the first statement after the structure 61

breakand continuestatements continue is used in while, for, and do while structures When executed in a loop It skips remaining statements and proceeds with the next iteration of the loop 62

break and continue Statements break for (i=0; i<10; i++) { } if (i==5) break; cout << << i; continue for (i=0; i<10; i++) { if (i==5) continue; cout << << i; } 0 1 2 3 4 0 1 2 3 4 6 7 8 9 63

Nested Control Structures Print N stars for (j = 1; j <= N; j++) cout << "*"; Print the numbers from 1 to 5, one per line for (i = 1; i <= 5 ; i++) { cout << i; cout << endl; } 64

Nested Control Structures Create and print the following pattern: * ** *** On line i print i stars **** ***** Code: for (i = 1; i <= 5 ; i++) { for (j = 1; j <= i; j++) cout << "*"; cout << endl; } 65

Nested Control Structures Create and print the following pattern: ***** **** *** ** * Code: for (i = 5; i >= 1; i--) { for (j = 1; j <= i; j++) cout << "*"; cout << endl; } On line 5-i-1 print i stars / decreasing order 66

Nested Control Structures Create and print the following pattern: * ** *** **** ***** Code: On line i print 5-i spaces and i stars for (i = 1; i <= 5 ; i++) { for (j = 1; j <= 5-i; j++) cout << "; for (j = 1; j <= i; j++) cout << "*"; cout << endl; } 67

Nested Control Structures Pattern: * ** *** **** ***** **** *** ** * Code: for (i = 1; i <= 5 ; i++) { for (j = 1; j <= i; j++) cout << "*"; cout << endl; } for (i = 4; i >= 1; i--) { for (j = 1; j <= i; j++) cout << "*"; cout << endl; } 68

Avoiding Bugs by Avoiding Patches Software patch Piece of code written on top of an existing piece of code Intended to fix a bug in the original code Some programmers address the symptom of the problem by adding a software patch Should instead resolve underlying issue 69

Debugging Loops Loops are harder to debug than sequence and selection structures Use loop invariant Set of statements that remains true each time the loop body is executed Most common error associated with loops is off-by-one 70

Summary C++ has three looping (repetition) structures: while, for, and do while while and for loops are called pretest loops do...while loop is called a posttest loop while and for may not execute at all, but do...while always executes at least once 71

Summary while: expression is the decision maker, and the statement is the body of the loop A while loop can be: Counter-controlled Sentinel-controlled Flag-controlled EOF-controlled for loop: simplifies the writing of a counter-controlled while loop Executing a break statement in the body of a loop immediately terminates the loop Executing a continue statement in the body of a loop skips to the next iteration 72