REPETITION CONTROL STRUCTURE

Slides:



Advertisements
Similar presentations
Computer Science 1620 Loops.
Advertisements

1 Lecture 11:Control Structures II (Repetition) (cont.) Introduction to Computer Science Spring 2006.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
Chapter 5: Control Structures II (Repetition)
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Chapter 5: Control Structures II (Repetition)
Chapter 5: Loops and Files.
Chapter 5: Control Structures II (Repetition)
CHAPTER 5 CONTROL STRUCTURES II (Repetition). In this chapter, you will:  Learn about repetition (looping) control structures  Explore how to construct.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
Chapter 5: Control Structures II (Repetition)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 5: Control Structures II (Repetition)
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 5: Control Structures II
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Loops and Files. 5.1 The Increment and Decrement Operators.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
Chapter 4 Repetition Structures
Topic 4: Looping Statements
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Unit 3 Lesson 9 Repetition Statements (Loops)
Chapter 5: Control Structures II (Repetition)
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
Chapter 5: Control Structures II
Chapter 5: Control Structures II
Chapter 5: Control Structures II
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
Control Structures II (Repetition)
Repetition-Counter control Loop
Java Programming: Guided Learning with Early Objects
Chapter 2.2 Control Structures (Iteration)
( Iteration / Repetition / Looping )
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Chapter 5: Control Structures II
Lecture 4B More Repetition Richard Gesick
Control Structures - Repetition
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Iteration: Beyond the Basic PERFORM
Iteration: Beyond the Basic PERFORM
Control Statements Loops.
Chapter 6: Repetition Statements
Chapter 5: Control Structures II (Repetition)
Objectives You should be able to describe: The while Statement
Repetition Statements (Loops) - 2
Control Statements Loops.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Chapter 4 Repetition Structures
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

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

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

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.

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

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

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???

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 ++

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 ++

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

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

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

The for loop

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;

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.

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

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

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

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

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

for loop – Exercises Exercise 1 - answer

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;

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;

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

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

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

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;

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;

for loop – Exercises Exercise 4: answer

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:

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

The while loop

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

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

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

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

while loop The general form of while loop flowchart:

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

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

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

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

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

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:

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

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

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

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

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

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

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;

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

while loop – sentinel control General syntax :

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

while loop – sentinel control Output screen

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

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

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;

while loop – sentinel control Output

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:

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();

The do … while loop

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

do … while loop General form of flowchart:

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)

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

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

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

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

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.

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)

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)

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)

do … while loop Answer: INFINITE LOOP!

Nested Control Structures

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.

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

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

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

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.

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

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

The jump statements

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

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

Thank You ! www.themegallery.com