Advanced loop controls. Loop Controls Recall from last week loop controls Event-controlled loops using sentinels repeats until a control variable takes.

Slides:



Advertisements
Similar presentations
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
Advertisements

True or false A variable of type char can hold the value 301. ( F )
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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
A loop is a repetition control structure. it causes a single statement or block to be executed repeatedly What is a loop?
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Chapter 5: Loops and Files.
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
1 Chapter 6 Looping Dale/Weems/Headington. 2 l Physical order vs. logical order l A loop is a repetition control structure based on a condition. l it.
Chapter 5: Control Structures II (Repetition)
CS 1 Lesson 5 Loops and Files CS 1 -- John Cole.
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.
Chapter 5: Control Structures II (Repetition)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
Chapter 6 Looping.
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.
1 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops.
1 Chapter 9 Additional Control Structures Dale/Weems/Headington.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
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 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
1 Do-While Statement Is a looping control structure in which the loop condition is tested after each iteration of the loop. SYNTAX do { Statement } while.
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.
Chapter 7 Additional Control Structures. Chapter 7 Topics l Switch Statement for Multi-Way Branching l Do-While Statement for Looping l For Statement.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
CSIS 113A Lecture 5 Random Numbers, while, do-while.
Chapter 6 Looping CS185/09 - Introduction to Programming Caldwell College.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
1 Looping. 2 Chapter 6 Topics  While Statement Syntax  Phases of Loop Execution  Two Types of Loops: Count-Controlled Loops &Event-Controlled Loops.
Chapter 05 (Part III) Control Statements: Part II.
Control Structures Repetition or Iteration or Looping Part II.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Loops and Files. 5.1 The Increment and Decrement Operators.
A loop is a repetition control structure. body - statements to be repeated control statement - decides whether another repetition needs to be made leading.
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.
Looping ROBERT REVAES. Logical Operators  && AND  Both have to be true for it to evaluate to be true.  || OR  One or the other has to be true for.
1 For Loops l From Chapter 9 l A shorthand way of coding count loops.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Chapter 6 Looping. 2 l A loop is a repetition control structure. l it causes a single statement or block to be executed repeatedly What is a loop?
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.
Control Structures Repetition or Iteration or Looping Part II.
Chapter 5: Control Structures II (Repetition)
Control Structures - Repetition
Looping and Repetition
Additional Control Structures
Chapter 7 Additional Control Structures
Chapter 5: Control Structures II (Repetition)
do/while Selection Structure
Control Statements Paritosh Srivastava.
Looping and Repetition
Presentation transcript:

Advanced loop controls

Loop Controls Recall from last week loop controls Event-controlled loops using sentinels repeats until a control variable takes on a certain value do – while loops Controlling loops with break and continue statements Control with exit() two value functions – loops within loops reading from files using timers random numbers

Simple sentinel example Running totals using a count sentinel count =0; \\count = 1? total = 0; while (count > num; total = total + num; cout “The total is now “ << total <<endl; count++; }

flag = 1; while ( flag ) { total = total + num; cout “\nThe total is now “ << total; cout << “Enter a number: “; cin >> num; if( num > 999) flag = 0; } Sentinel Example Running Total Using a Flag

Sentinel Example Running Total Using a Value Sentinel cout << “\nEnter a number: “; cin >> num; while ( num != 999) { Total = total + num; cout “\nThe total is now “ << total; cout << “enter a number: “; cin >> num; } } initial read

break and continue Statements Interrupt the normal flow of control. break causes an exit from innermost enclosing loop or switch statement. continue cause current iteration of a loop to stop and the next iteration to begin immediately. Try not to use them at all. Confuses readability continue are only be used in while, for, and do loops not in if or switch selection statements.

The break Statement int j =50; while (j < 80){ j += 10; if (j == 70) break; cout << “j is “ << j<< ‘\n’; } cout << “We are out of the loop.\n”; demo1 chris

The continue Statement int j =50; while (j < 80){ j += 10; if (j == 70) continue; //skip 70 cout << “j is “ << j<< ‘\n’; } cout << “We are out of the loop.\n”; demo2 Chris

break and continue while ( ) { statement-1; if( )continue statement-2; } statement-3; while ( ) { statement-1; if( ) break statement-2; } statement-3;

The do – while Post test loop Variant of the while statement Syntax do do { statements while } while (expression); next statement

Example: do { cout > age; if (age <=0) cout << “Invalid age.\n”; else cout << "DO SOMETHING\n"; } while (age <=0) ; data validation with do-while

cout << "Enter your age: "; cin >> age; while while (age <= 0) { if (age <=0) { cout << "Invalid age.\n"; cout << "Enter your age: "; cin >> age; } else cout << "DO SOMETHING\n"; } while version Setup loop start condition

sum = 0; cnt = 1; do { I/O sum += cnt; cnt++; } while (cnt <=n); sum = 0; cnt = 1; I/O // priming read while (cnt <=n) { I/O sum += cnt; cnt++; } do vs. while

Guidelines for choosing: If simple count-controlled, use a for. If event-controlled and body is executed at least once, use do-while. If event-controlled and nothing is known about the first execution, use while. When in doubt use while?

Techniques Two value functions for (row = 1; row <=600; row++) { for (col = 1; col <=800; col++) { val = F(col,row); } How many times is the function F called ? 480,000

Techniques Two value functions for (x = 1; x <=1000; x++) { for (y = 1; y <=1000; x++) { for (z = 1;z<=1000;z++) { val = F(x,y); } How many times is the function F called ? 1,000,000,000 1 billion times! demonstrate Chris

#include float F(float, float); int main() { float x, y; for (y = 1; y <= 12; y = y + 1) { for (x=1; x <=12; x = x + 1) { cout << setw(5) << x*y; } cout << endl; } return 0; } What does this program output? You must be able to work out what is going on!

Techniques Time for delays Time for performance measures

Timers Delay execution for a short time Measure performance of processes Real time simulations Control systems washing machines, traffic lights, nuclear power stations clock returns the number of clock ticks of elapsed processor time. The returned value is the product of the amount of time that has elapsed since the start of a process and the value of the CLOCKS_PER_SEC constant. If the amount of elapsed time is unavailable, the function returns –1, cast as a clock_t. In other words, clock returns the number of processor timer ticks that have elapsed. A timer tick is approximately equal to 1/CLOCKS_PER_SEC second.

Delays design initialise a variable that holds desired delay in seconds say initialise a variable (start_time) that holds the current time construct a loop that repeatedly gets the current time and assigns it to a variable called current_time check whether difference between start_time and current_time is greater than desired delay if it is break out of loop

CODE SEGMENT #include // for clock_t data type clock_t start_time; clock_t current_time; clock_t wait = 3* CLOCKS_PER_SEC;//note milliseconds start_time = clock(); do { current_time = clock(); } while(current_time – start_time <= wait);

Measuring Performance cout << "Time to do "<< j << " function calls is "; start = clock(); while( j-- ) sqrt(i); finish = clock(); duration2 = (double)(finish - start) / CLOCKS_PER_SEC; cout << duration2 <<" seconds\n"; get the time before segment to test get the time after segment complete compute difference in time. e.g. find out speed of calling functions

#include void sleep( clock_t wait ); void main( void ) { long i = L; int t = 10; clock_t start, finish; double duration1, duration2; /* countdown! */ do { sleep(1 * CLOCKS_PER_SEC); cout << t << endl; t--; } while (t >0); sleep(1 * CLOCKS_PER_SEC); cout << "Blast off!" << endl << endl; // Measure the duration of an event. cout << "Time to do " << i << " empty loops is "; start = clock(); while( i-- ); finish = clock(); duration1 = (double)(finish - start) / CLOCKS_PER_SEC; cout << duration1 <<" seconds\n"; /* Measure the duration of an event. */ cout << "Time to do "<< j << " function calls is "; start = clock(); while( j-- ) sqrt(i); finish = clock(); duration2 = (double)(finish - start) / CLOCKS_PER_SEC; cout << duration2 <<" seconds\n"; cout << "duration1 is " << duration2 / duration1 << " Times faster" << endl; } /* Pauses for a specified number of milliseconds. */ void sleep( clock_t wait ) { clock_t start_time; clock_t current_time; start_time = clock(); do { current_time = clock(); } while(current_time – start_time <= wait); } DO TIMER DEMO CHRIS

Simulators timers and random numbers Traffic light simulation Given initial state traffic light changes at random intervals in real time. in 2 x real time. need random numbers rand() and srand() in #include

Random numbers (DEMO CHRIS) /* This program seeds the random-number generator with the time, then displays 10 random integers. */ #include int main( void ) { int i; int maxval = 100; /* Seed the random-number generator with current time so that the numbers will be different every time we run. */ srand( (unsigned)time( NULL ) ); /* Display 10 numbers. */ for( i = 0; i < 10;i++ ) cout << 1 + rand() % maxval ; return 0; }

Traffic lights Simulator program #include void sleep( clock_t wait ); int main() { const int RED = 1; const int GREEN = 2; const int ORANGE = 3; int CurrentLight = RED; int wait; srand( (unsigned)time( NULL ) ); // seed the random number generator; cout <<"RED" << endl; wait = 1 + rand() % 5; sleep(wait); // change light while (!kbhit()) { if (CurrentLight == RED) { CurrentLight = GREEN; cout << "GREEN" << endl; wait = 1 + rand() % 10; sleep(wait); } else if (CurrentLight == GREEN) { CurrentLight = ORANGE; cout << "ORANGE" << endl; wait = 1 + rand() % 10; sleep(2); } else { CurrentLight = RED; cout << "RED" << endl; wait = 1 + rand() % 10; sleep(wait); } return 0; } void sleep( clock_t wait ) { clock_t goal; wait = wait *CLOCKS_PER_SEC; goal = wait + clock(); while( goal > clock() ) ; }

Basic reading of files File location where file is stored can be interactive File format Structure of file examples words.dat and sussex.dat year followed by data for each of 12 months each column is ave low temp, ave high temp, ave temp, in Fahrenheit and rain in inches End of File marker a byte = EOF (constant) needs a variable to check

File Processing Open file check success if failure exit(1); keep reading from file and checking for EOF until EOF found needs knowledge of format Do the necessary processing Close file

Open a file need #include need special ifstream variable e.g. ifstream infile; need to initialise variable with call infile.open("c:\\words.dat", ios::nocreate); need to check success if (infile == NULL) exit(1); // catastrophic error! Now can set up a loop to repeatedly read from file until end

File read loop – while((ch= infile.peek()) != EOF) { infile >> word; size = strlen(word); if (max < size) { max = size; } if (min > size) { min = size; } cout << word << endl; } Reads every word, finds out how long each word is. and then displays the word.

Close the file Once done do the housework infile.close()

#include int main(void) { ifstream infile; int ch; char word[30]; int size; int max = 0; int min = 100; infile.open("c:\\words.dat", ios::nocreate); if (infile == NULL) { cout << "Error"; exit(1); } while((ch= infile.peek()) != EOF) { infile >> word; size = strlen(word); if (max < size) {max = size; strcpy(maxword,word);} if (min > size) {min = size; strcpy(minword,word);} cout << word << endl; } cout << max << '\t'<< maxword <<'\t'<< min << '\t'<< minword << endl; infile.close(); return 0; }