REPETITION CONTROL STRUCTURE LOGO

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

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

Why Is Repetition Needed?

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

Chapter 5: Control Structures II (Repetition)

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

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

Increment and the While. Class 15

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

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

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

Repetition Structures

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

Introduction. C provides two styles of flow control:

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

Lecture 7 Tao Wang 1

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

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

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

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

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

LECTURE 5 Control Structures Part 2

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

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

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

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

Unit 3 Decision making, Looping and Arrays

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.

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

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

Chapter 5: Loops and Files

Looping. Arizona State University 1

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

C++ PROGRAMMING SKILLS Part 2 Programming Structures

Repetition and Loop Statements Chapter 5

Unit 7. 'while' Loops

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

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

Programming Fundamentals

DELHI PUBLIC SCHOOL TAPI

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

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

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

In this chapter you will learn:

STUDENT LESSON A12 Iterations

C++ Final Exam 2017/2018

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

An Introduction to Programming with C++ Sixth Edition. Chapter 7 The Repetition Structure

Control Structures of C++ Programming (2)

Chapter 4: Control structures. Repetition

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

n Group of statements that are executed repeatedly while some condition remains true

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Prepared by: Shraddha Modi

Loops and Files. of do-while loop

Dept. of CSE, IIT KGP

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

Chapter 4: Control structures

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 5. Repetition in Programs. Notes. Notes. Notes. Lecture 05 - Loops

204111: Computer and Programming

Loops / Repetition Statements

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

Computer Programming I - Unit 5 Lecture page 1 of 14

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

Flow Control. CSC215 Lecture

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

Information Science 1

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

CSCE150A. Introduction. While Loop. Compound Assignment. For Loop. Loop Design. Nested Loops. Do-While Loop. Programming Tips CSCE150A.

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

3 The L oop Control Structure

Building on the foundation. Now that we know a little about cout cin math operators boolean operators making decisions using if statements

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

Unit 5. Decision Making and Looping. School of Science and Technology INTRODUCTION

Control Structures II. Repetition (Loops)

Loops (while and for)

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

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

Chapter 5: Control Structures

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

CHAPTER : 9 FLOW OF CONTROL

LOOPS. Repetition using the while statement

Module 4: Decision-making and forming loops

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

Information Science 1

Chapter 3 Problem Solving and the Computer

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

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

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

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Chapter 2: Functions and Control Structures

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

LECTURE NOTES ON PROGRAMMING FUNDAMENTAL USING C++ LANGUAGE

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

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

Score score < score < score < 65 Score < 50

Problem Solving With Loops

Transcription:

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

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

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. 3

Introduction Two types of loop: Pretest 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 4

Introduction Repeat sequence of instruction many times (as long as condition is TRUE ) Repetition = iteration = loop Similar function, different names Example You have to create a simple program that will receive 5 integer inputs from user. Sum those 5 inputs and calculate the average. Check out the C++ code with and without looping 5

Introduction A program that will receive 5 integer inputs from user and sum those 5 inputs and calculate the average. /* Problem: Sum 5 numbers, calculate the average, display the results */ Is this what you are thinking??? int num1, num2, num3, num4, num5; int sum; float average; cin>>num1>>num2>>num3>>num4>>num5; sum = num1 + num2 + num3 + num4 + num5; average = sum / 5; cout<<"sum: "<<sum<<"\taverage: "<<average; 6

Introduction The correct way by using repetition Solution int num, sum = 0, count = 0; using float average; while(count < 5) looping!!! { cout<<"num "<<(count + 1)<<": "; cin>>num; sum = sum + num; count = count + 1; } average = sum / 5; cout<<"sum: "<<sum<<"\taverage: "<<average; 7

Types of Repetition Statement Types of repetition for while do while 8

Types of Repetition Structure Types of repetition structure Counter-controlled repetition Number of repetition is fixed (known in advance) e.g. repeat a process 10 times Sentinel-controlled repetition Stop looping whenever a special value is entered e.g. enter -1 to end the loop Flag-controlled repetition When a defined value is matched, it stops looping, else loop will continue e.g. looping will continue 1000 times, however it will stop immediately if the value entered by user matches with ID = 102 9

Requirements of Repetition /* example using while loop */ int i = 0; //initialize while(i < 10) { statements; i++; } Loop Body Loop Condition Loop Control Variable (LCV) 10

Requirements of Repetition /* example using for loop */ for(i = 0; i < 10; i++) { statements; } Loop Control Variable (LCV) Loop Body Loop Condition 11

Requirements of Repetition Loop Control Variable (LCV) A variable whose value determines whether the loop body will be executed or not It has initial value and increment/decrement value Loop Condition If the condition is true, the loop body is executed; if condition is false the loop exits Loop Body A block of statements to be repeated 12

Requirements of Repetition Execution of loop body is controlled by 3 operations: Initialization of the LCV Evaluation of LCV in the loop condition Update of the LCV by incrementing (e.g. x++) or decrementing (e.g. x--) 13

Requirements of Repetition Increment operator Table 4.1: Increment operator Common Equivalent to statement x++ x = x + 1 x += 1 - x = x + 3? -? x += 5 - x = x + i? 14

Requirements of Repetition Decrement operator Table 4.2: Decrement operator Common Equivalent to statement x-- x = x - 1 x -= 1 - x = x - 9? -? x -= 2 -? x -= sum 15

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

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

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

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

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

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

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

The for loop 23

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

for loop 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). 3. Repeat Step 2 until the loop condition evaluates to false. The initial statement usually initializes a variable. In C++, for is a reserved word. 25

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 26

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 27

for loop Example 1 Flowchart Start i = 0 i <= 10 F End T Display welcome to C++ i ++ 28

for loop Example 1 29

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

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

for loop Exercises Exercise 1 - answer 32

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

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

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

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 36

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

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; 38

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 << "Enter a number : "; cin >> num; } cout << sum << endl; 39

for loop Exercises Exercise 4: answer 40

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: 41

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

The while loop 43

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

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 45

while loop 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 46

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 47

while loop The general form of while loop flowchart: 48

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

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

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

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

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

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: 54

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 55

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

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

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

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

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

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; } 61

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 62

while loop sentinel control General syntax : 63

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') Sentinel value { cout << "Welcome to the program." << endl; cout << "Do you want to quit (Y - Yes, N - No) : "; cin >> answer; } cout << "Bye."; getch(); return 0; } 64

while loop sentinel control Output screen 65

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

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

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

while loop sentinel control Output 69

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: 70

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

The do while loop 72

do while loop The general form of a do...while statement is: do statement while (expression); 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 73

do while loop General form of flowchart: 74

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) 75

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

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

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

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

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. 80

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) 81

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) 82

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) 83

do while loop Answer: INFINITE LOOP! 84

Nested Control Structures 85

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. 86

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 ; 87

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

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. 89

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. 90

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

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: ***** **** *** ** * 92

The jump statements 93

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; } 1 2 3 4 loop terminated at x: 5 Press any key to continue 94

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; } 1 2 3 4 6 7 8 9 10 the number 5 is not printed Press any key to continue 95

www.themegallery.com 96