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