110 likes | 206 Views
CMPT 128: Introduction to Computing Science for Engineering Students. , continue ; and break; statements. Avoid infinite loops. Can infinite loops ever be useful? Yes, but usually there is a safer way to do the same thing Should you purposely write and infinite loop? Generally not
E N D
CMPT 128: Introduction to Computing Science for Engineering Students , continue; and break; statements
Avoid infinite loops • Can infinite loops ever be useful? • Yes, but usually there is a safer way to do the same thing • Should you purposely write and infinite loop? • Generally not • For some specific purposes, if you are very careful and know that the loop will be terminated regardless of the path taken through the program, an infinite loop may be useful.
Exiting a loop before it completes • Sometimes you wish to exit from a loop even if the loop condition is still true • For example if your loop is reading and processing data and an error occurs that can be recognized but cannot be corrected, you may wish to print an error message and exit the loop immediately • How do you exit a loop while the loop condition is true? Use a break statement
The break Statement: • break; • A C++ statement that causes you to exit the loop you are in • Program execution will continue at the statement following the loop
break statement Condition Loop condition F T Statement 1; ….. T condition2 break; F ….. Statement n;
Example: break // Read and sum an unknown number of positive integers // Stop reading +ve integers when you read a -ve integer sum = 0; count = 0; while ( count < 10000000 ) // Safer than infinite loop { cin>> nextint; if( nextint < 0 ) break; sum += nextint; count++; } cout << sum;
Executing only some statements in a loop • Sometimes you wish to execute a block of statements inside your loop only under particular conditions • For example you may wish to skip the last half of the body of the loop if divisor = 0 (so you will not divide by 0) • How do you execute only some of the statements inside the loop? Use a continue statement
The continue Statement: • continue; • A C++ statement that causes you to go from anywhere in the loop to the (update statement and loop condition test) • Program execution will continue at the first statement inside the loop after the loop variable has been incremented and tested (if the test indicates another pass through the loop)
continue statement Condition F T Statement 1; ….. T condition2 continue; F ….. Statement n;
Example: continue // Sum the even integers from 1 to 35 x = 0; sum = 0; while ( x <= 35 ) { x++; if ( x % 2 == 1 ) continue; sum += x; } cout << sum;
Example: continue // Determine the kilometers per litre intlitres = 0; int kilometers = 0; x = 0; while ( x < 1000 ) { cout << “enter #of liters and # kilometers”; cin >> litres >> kilometers ; x++; if ( litres == 0 ) continue; cout << “kilometers/liter “ << kilometers / litres; }