TOPIC 4: REPETITION CONTROL STRUCTURE

Slides:



Advertisements
Similar presentations
True or false A variable of type char can hold the value 301. ( F )
Advertisements

Computer Science 1620 Loops.
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 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Computer Programming 1 Repetition. Computer Programming 2 Objectives Repetition structures Study while and do loops Examine for loops A practical example.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
CHAPTER 5 CONTROL STRUCTURES II (Repetition). In this chapter, you will:  Learn about repetition (looping) control structures  Explore how to construct.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
1 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Chapter 4 Loops Write code that prints out the numbers Very often, we want to repeat a (group of) statement(s). In C++, we have 3 major ways of.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
Chapter 5 Loops. Overview u Loop Statement Syntax  Loop Statement Structure: while, for, do-while u Count-Controlled Loops u Nested Loops u Loop Testing.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
1 09/20/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Control Structures Repetition or Iteration or Looping Part II.
Chapter 5: Control Structures II
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
Control Structures RepetitionorIterationorLooping Part I.
Overview Go over parts of quiz? Another iteration structure for loop.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
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.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Chapter 5: Loops. Slide 5- 2 Outline Increment and Decrement while loop do-while loop for loop.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
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
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
Chapter 2.2 Control Structures (Iteration)
( Iteration / Repetition / Looping )
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.
Lecture 4B More Repetition Richard Gesick
Control Structures - Repetition
Logical Operators and While Loops
Control Structures Lecture 7.
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.
Additional Control Structures
Chapter 2.2 Control Structures (Iteration)
Structured Program Development in C
Let’s all Repeat Together
Logical Operators and While Loops
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Chapter 4 Repetition Structures
Programming Fundamental
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Programming Fundamental
Presentation transcript:

TOPIC 4: REPETITION CONTROL STRUCTURE Eizan Aziz CSC128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING EA | CSC128 | TOPIC04 11/15/2018

OUTLINE Introduction Types of Repetition Statement Requirements of Repetition while loop for loop do...while loop break statement continue statement Counter-controlled loop Sentinel-controlled loop Flag-controlled loop EA | CSC128 | TOPIC04 11/15/2018

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 EA | CSC128 | TOPIC04 11/15/2018

Is this what you are thinking??? Introduction /* Problem: Sum 5 numbers, calculate the average, display the results */ 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; Is this what you are thinking??? EA | CSC128 | TOPIC04 11/15/2018

Solution using looping!!! Introduction Solution using looping!!! int num, sum = 0, count = 0; float average; while(count < 5) { cout<<"Num "<<(count + 1)<<": "; cin>>num; sum = sum + num; count = count + 1; } average = sum / 5; cout<<"Sum: "<<sum<<"\tAverage: "<<average; EA | CSC128 | TOPIC04 11/15/2018

Types of Repetition Statement for while do…while EA | CSC128 | TOPIC04 11/15/2018

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 EA | CSC128 | TOPIC04 11/15/2018

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

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

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; otherwise the loop exits Loop Body A block of statements to be repeated EA | CSC128 | TOPIC04 11/15/2018

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--) EA | CSC128 | TOPIC04 11/15/2018

Requirements of Repetition Increment operator Table 4.1: Increment operator Common statement Equivalent to x++ x = x + 1 x += 1 - x = x + 3 ? x += 5 x = x + i EA | CSC128 | TOPIC04 11/15/2018

Requirements of Repetition Decrement operator Table 4.2: Decrement operator Common statement Equivalent to x-- x = x - 1 x -= 1 - x = x - 9 ? x -= 2 x -= sum EA | CSC128 | TOPIC04 11/15/2018

while loop while(expression) { statements; } Expression is evaluated first and then executes the statement. If the expression is evaluate to true, it continue to be executed, and if the expression is evaluate to false, it exit the while loop. Syntax/structure: while(expression) { statements; } EA | CSC128 | TOPIC04 11/15/2018

while loop Flowchart EA | CSC128 | TOPIC04 11/15/2018

A) Initialization of LCV B) Evaluation of LCV in loop condition while loop A) Initialization of LCV C++ code segment /* file: topic_4_while_00.cpp */ int count = 0; while (count < 5) { cout<<"continue looping "; cout<<count<<"\n"; count++; } cout<<"stop looping at count "<<count; B) Evaluation of LCV in loop condition D) Update LCV C) Loop body EA | CSC128 | TOPIC04 11/15/2018

while loop C++ output based on Slide 16 EA | CSC128 | TOPIC04 11/15/2018

while loop How to do tracing? Statement T continue looping 0 1 count count < 5 Statement count++ T continue looping 0 1 continue looping 1 2 continue looping 2 3 continue looping 3 4 continue looping 4 5 F stop looping at count 5 EA | CSC128 | TOPIC04 11/15/2018

What is the value of Total Sum? Exercise 1 – while loop /* file: topic_4_exe_01_while.cpp */ int num = 1, sum = 0; while ( num < 15 ) { sum = sum + num; num = num + 3; } cout << "Total sum: " << sum; What is the value of Total Sum? EA | CSC128 | TOPIC04 11/15/2018

Try it out at Borland C++ Exercise 2 – while loop /* file:topic_4_exe_02_while.cpp */ int guess; int numberToGuess = 27; cin >> guess; while ( guess != numberToGuess ) { cout << "Sorry! Wrong number."; cout << "Keep Guessing!\n"; } cout << "Congrats!"; Try it out at Borland C++ EA | CSC128 | TOPIC04 11/15/2018

Exercise 3 – while loop Write a program using while loop to find the sum of integers 73 through 415 inclusive File: topic_4_exe_03_while.cpp EA | CSC128 | TOPIC04 11/15/2018

Homework 1– while loop Homework File: topic_4_hw_01_while.cpp Make the user guess a magic number. Tell them if their number was either below or above the one they guess. If user enters correct number, stop the looping and display “Congratulation!”. Write C++ program. File: topic_4_hw_01_while.cpp EA | CSC128 | TOPIC04 11/15/2018

Homework 2– while loop Homework - Guess Number Game Player will enter a special character to start and continue the game. Prompt a message to user asking to enter a guess number into the program. If guess number exactly similar to magic number, display a message “Congrats!” and use break statement to quit the iteration, else, display a message “Wrong!” and a question to continue the game. If player enters invalid special character, quit the iteration statement. Finally, display “Number of Attempt” value. In order to get number of attempt value, use counter every time player enters special character to start/continue the game. File: topic_4_hw_02_while.cpp EA | CSC128 | TOPIC04 11/15/2018

Quit looping & continue the rest of the program for loop Categorized as counter-controlled loop because it manages repetition through counting Syntax/structure for (initialization; condition; update LCV) {   statements; } 1 4 A B D 2, TRUE 3 C FALSE Quit looping & continue the rest of the program EA | CSC128 | TOPIC04 11/15/2018

for loop How it works? The variable(s) is initialized The condition is checked. If true, execute statements, else terminate for loop Execute statements within for loop Update variables and return to step B EA | CSC128 | TOPIC04 11/15/2018

for loop Flowchart EA | CSC128 | TOPIC04 11/15/2018

Evaluation of LCV in loop condition for loop Initialization of LCV C++ code segment Evaluation of LCV in loop condition /* file: topic_4_for_00.cpp */ int count; for (count = 0 ; count < 10 ; count++) { cout<< "continue looping " ; cout<< count << "\n" ; } cout << "stop looping at count " << count; Loop body Update LCV EA | CSC128 | TOPIC04 11/15/2018

Try it out at Borland C++ Exercise 1 – for loop /* file: topic_4_exe_01_for.cpp */ int sum = 0, num; for( int count = 0 ; count < 5 ; count++ ) { cout << "\nEnter a number : "; cin >> num; sum = sum + num; } cout << "\nTotal sum : " << sum; Try it out at Borland C++ EA | CSC128 | TOPIC04 11/15/2018

Exercise 2 – for loop /* file: topic_4_exe_02_for.cpp */ int x; cout << "The output is...\n\n"; for ( x = 0; x < 10; x++ ) { if( x % 2 == 0) cout << "\t *"; else cout << "\n"; } EA | CSC128 | TOPIC04 11/15/2018

Exercise 3 – for loop /* file: topic_4_exe_03_for.cpp */ int x, y; cout << "The output is...\n\n"; for ( x = 0; x < 5; x++ ) { for ( y = x; y < 5; y++ ) cout << "\t*"; } cout << "\n"; EA | CSC128 | TOPIC04 11/15/2018

Homework 1– for loop Homework Draw the tracing table and show the output /* file: topic_4_hw_01_for.cpp */ #include <iostream.h> #include <conio.h> void main() { for ( int n = 1 ; n != 15 ; n++ ) cout << n << " "; } getch(); EA | CSC128 | TOPIC04 11/15/2018

break statement The break statement is used at the end of the cases of a switch statement to avoid flow of control falling through to the next case. It can also, but should not, be used inside the bodies of iterations. The break statement is used to escape from an iteration loop or a switch statement. EA | CSC128 | TOPIC04 11/15/2018

break statement Upon evaluating the expression-2 to true, the break statement will exit from the while loop resulting the statement-2 to be skipped. Next statement-3 will be executed. Example in while loop while ( expression-1 ) { statement-1; if ( expression-2 ) break; statement-2; } statement-3; EA | CSC128 | TOPIC04 11/15/2018

break statement If value of x is 1, matched with case 1, then executes statement-1. once it is done, break statement will exit from switch statement and executes statement-4. Example in switch int x; cin>>x; switch(x) { case 1: statement-1; break; case 2: statement-2; default: statement-3; } statement-4; EA | CSC128 | TOPIC04 11/15/2018

break statement What is the output??? Test your knowledge int x; for (x = 1; x <= 10; x++) { if (x == 5) break; cout << x << " "; } cout << "\nThe loop terminated at x = " << x; What is the output??? EA | CSC128 | TOPIC04 11/15/2018

continue statement Perform similar function as break statement but, break statement terminate/quit the loop, continue statement goes back to the beginning of the loop’s block to start new iteration EA | CSC128 | TOPIC04 11/15/2018

continue statement int n; for(int x = 0; x < 5; x++) { cout << "Enter a number: "; cin >> n; if(n == 2) break; else continue; } cout <<"You just typed in 2!\n"; cout <<"and it called the break statement!"; If value of n is 2, looping will stop else it will continue to the next loop EA | CSC128 | TOPIC04 11/15/2018

Counter-controlled loop Number of repetition is known in advance e.g: repeat a process 10 times. Meaning, 1 process will be repeated 10 times. /* example using for loop */ int x; for (x = 0; x < 10; x++) { cout << "i will study hard "; cout << "no matter how hard "; cout << "c++ programming is."; } EA | CSC128 | TOPIC04 11/15/2018

Counter-controlled loop /* example using while loop */ int total, gradeCounter, grade, average; total = 0; gradeCounter = 1; while (gradeCounter <= 10) { cout << "Enter grade: "; cin >> grade; total = total + grade; gradeCounter = gradeCounter + 1; } average = total / 10; cout << "Class average is " << average; EA | CSC128 | TOPIC04 11/15/2018

Logical Thinking Test Test 1 Test 2 Your program should be able to receive 2 inputs entered by user Determine smallest and largest input Test 2 Your program should be able to receive 3 inputs entered by user EA | CSC128 | TOPIC04 11/15/2018

Exercise 1 - Counter-controlled loop Write a complete C++ program to find smallest and largest number from a sequence of five integers input from keyboard. Problem definition Input: Any 5 numbers Process: Accept the number and determine smallest and largest Output: maximum and minimum File: topic_04_mix_max_01.cpp EA | CSC128 | TOPIC04 11/15/2018

Exercise 2 - Counter-controlled loop Write a complete C++ program to find the largest of sequence of integers. The number of integers is determined by user. Problem definition Input: number, totalNumber Process: Accept numbers and compare to the largest Output: largest File: topic_04_largest_01.cpp EA | CSC128 | TOPIC04 11/15/2018

do…while loop do { statements; } while(expression); Execute the statements (loop body) first, then check expression/condition Syntax/structure: do { statements; } while(expression); EA | CSC128 | TOPIC04 11/15/2018

do…while loop Flowchart EA | CSC128 | TOPIC04 11/15/2018

do…while loop /* file: topic_4_dowhile_00.cpp */ int count = 0; do { cout<<"continue looping "; cout<<count<<"\n"; count++; } while (count < 5); cout<<"stop looping at count "<<count; EA | CSC128 | TOPIC04 11/15/2018

while vs do…while While Do…while Initialize Check expression Execute loop body if expression return TRUE Update LCV Execute loop body Check expression, if TRUE, continue execute loop body EA | CSC128 | TOPIC04 11/15/2018

Sentinel-controlled loop Used when the exact number of repetitions is not known in advance or the items are too numerous to count beforehand. Thus, some loops require the user to enter a special value to end the loop. This special value is called the sentinel value. The integer and character value can be used as a sentinel value. Refer to Homework 2 – while loop at Slide 23 EA | CSC128 | TOPIC04 11/15/2018

Sentinel-controlled loop int specialChar = 0, count = 0, sum = 0; int average, number; cout << "Enter a number (0 - Quit): "; cin >> number; while (number != specialChar) { sum = sum + number; count = count + 1; cout << "\nEnter a number (0 - Quit): "; } average = sum / count; cout << "\nNumber of looping: " << count; cout << "\nAverage: "<<average;   EA | CSC128 | TOPIC04 11/15/2018

Sentinel-controlled loop int count = 0, sum = 0, average, number; char continueChar = 'Y', specialChar; do { cout << "\nEnter a number: "; cin >> number; sum = sum + number; count = count + 1; cout << "\nDo you want to continue? "; cin >> specialChar; } while (specialChar == continueChar); average = sum / count; cout << "\nNumber of looping: " << count; cout << "\nAverage: "<<average;   EA | CSC128 | TOPIC04 11/15/2018

Flag-controlled loop A flag is a boolean variable which the value is either True or False Syntax/structure bool found = false; //initialize LCV while(!found) //test LCV { ... if(expression) found = true; //update LCV } EA | CSC128 | TOPIC04 11/15/2018

Flag-controlled loop int numOfPlate; bool hungry = true; while(hungry) { cout << "How much you eat? "; cin >> numOfPlate; if(numOfPlate < 0) hungry = true; else hungry = false; } cout << "i am full!"; EA | CSC128 | TOPIC04 11/15/2018

Flag-controlled loop char answer; bool finished = false; while(!finished) { cout << "Did u finish ur job? "; cin >> answer; if(answer == 'Y' || answer == 'y') finished = true; else finished = false; } cout << "Good job!"; EA | CSC128 | TOPIC04 11/15/2018

Flag-controlled loop int sum, number; //sum of numbers read bool done; //used to control while loop sum = 0; //initialize the sum done = false; //initialize boolean variable while( !done ) //loop while not done { cin >> number; //read next number if(number > 0) //sum number if +ve sum = sum + number; //sum the number else done = true; //terminate loop } EA | CSC128 | TOPIC04 11/15/2018

Flag-controlled loop The loop logical expression ( !done ) indicates the loop should be executed as long as done is false. EA | CSC128 | TOPIC04 11/15/2018

Flag-controlled loop #include <iostream.h> #include <string.h>   void main() { char password[7]; char myPassword[7] = {"secret"}; bool pass = false; while (!pass) cout << "\n Enter your password "; cin >> password; EA | CSC128 | TOPIC04 11/15/2018

Flag-controlled loop if (strcmp(password,myPassword) == 0) { pass = true; } else cout << "\n\a Incorrect password"; } // close while loop cout << "\n Password accepted"; } // close void main() EA | CSC128 | TOPIC04 11/15/2018

End of Topic 04 EA | CSC128 | TOPIC04 11/15/2018