DOC PREVIEW
CSUN COMP 106 - Count-controlled Loops

This preview shows page 1-2 out of 5 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 5 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 5 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 5 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

The for loop March 9, 20061CountCount--controlled Loops controlled Loops ––the for the for Loop and Increment OperatorsLoop and Increment OperatorsLarry CarettoComputer Science 106Computing in Engineering and ScienceMarch 9, 20062Outline• Review last class– While and do while loops give test-before and test-after implementation of loops– Getting the right count and avoiding off-by-one errors• Count controlled loops and the for statement• Operators like += and ++ in for loops• Nested for loops3Review Basic Loop Structureswhile ( <condition>){// Repeated statements }do {// Repeated statements } while ( <condition>);4Review Tracing Loopscount = 0while (count < 3 ) {inFile << x << y;cout << x + y << endl;count = count + 1}• What is printed to screen for file data as follows: 1 2 3 4 5 6 7 8 9 10 11 1237115Review Correct Counts• Watch out for off-by-one errors caused by bad initial or final count values or by incorrect condition ( < vs. <= )• Look at loop counter settingscount = 0; // count = 1;do { // calculations and outputcount = count + 1}while ( count < 4 ); // count <= 4• How many times do we go through loop?Four times (count = 0, 1, 2, 3)6Loop Code Question• A data file has n sets of data on mass and velocity– The first number on the data file is the number of data sets, n– This is followed by individual data sets with mass given before velocity• Write the looping code that can read n and the data on mass and velocity data from the file and print the value of KE = mV2/2 for each data setThe for loop March 9, 200627Loop Code Answerdouble m, v; int n;ifstream inFile( “input.dat” );inFile >> n;int count = 0; // or = 1while ( count < n ) // or <= n{inFile >> m >> v;cout << “\nmass = “ << m <<“, velocity = “ << v <<“, KE = “ << m * v * v / 2;count = count + 1;}8Another Loop Question• The square root, x, of a number, A, (x2= A) can be found by the following iteration formula: x(n+1)= x(n)/2 + A/(2x(n))• For example if A = 2 and our initial guess, x(0), is 1 we obtain the following iteration sequence δ = | x(n+1)–x(n)|x(1)= ½ + 2/(2•1) = 1.5 δ = |1.5 – 1| = 0.5x(2)= 1.5/2 + 2 /(2•1.5) = 17/12 δ = 1/12x(3)= (17/12)/2 + 2 /(2•17/12) = 1.414216δ = 0.002459Another Loop Question II• Write a loop that uses the iteration formula x(n+1)= x(n)/2 + A/(2x(n)) to compute x, the square root of A– Declare x and A as type double and get a value of A from the user– Set an error tolerance, tol, = 10-12– Set the initial guess of x to 1– In the loop use the variables x for x(n+1)and xOld for x(n)to keep the previous value of x– Iterate until | x – xOld | ≤ tol * |x|10Another Loop Question III• How do your write this code– Iteration equation: x(n+1)= x(n)/2 + A/(2x(n)) – Iteration equation code: x = x/2 + A/(2x)• Left side x is x(n+1); right side x is x(n)– Before coding x = x/2 + …, code the statement xOld = x to remember x(n)– After execution of x = x/2 + A/(2x) the variable x contains x(n+1)and xOld contains x(n)– Use a do-while loop that continues iteration while |x(n+1)–x(n)| = | x – xOld | > tol * |x| = tol * |x(n)|• OK, now you can write the code!11Another Loop Question Answerdouble x, A, xOld, tol = 1e-12;cout << “This code finds the square “<< “ root of A; enter A: ”;cin >> A;x = 1;do{xOld = x;x = x / 2 + A / ( 2 * x );}while ( fabs( x – xold ) > tol *fabs( x ) );12Data Validation Loop Code• Place following code steps in loop• Get input from user in usual fashion (with input prompt)• Use if test to see if data is in range– If it is not in range, print error message and ask user for more data• Repeat code until input is correct– Typically use a do-while loopThe for loop March 9, 2006313Data Validation Loop Code IIint const minMonth = 1, maxMonth = 12;int month;bool badData;do{cout << “Enter the month” <<“ between “ << minMonth << “ and “ << maxMonth;cin >> month;badData = month < minMonth|| month > maxMonth14Data Validation Loop Code IIIif ( badData ){cout << “\n\nERROR You”<< “entered month = “<< month<< “\nReenter data”<< “ now.\n\n”;}}while ( badData );15Count-controlled loops• We have seen examples of while and do-while loops that use a counter• This is a common type of loop• A special command – the for loop – is designed for count-controlled loops• Examine count-controlled while loop• Look at equivalent for loop• Discuss general for loop syntax16Count-controlled Loopsint power = 2, maxNumber = 5;int counter = 0;While( counter < maxNumber ){result = pow( counter,power );cout << counter << "\t" << result << endl;counter = counter + 1;}InitializationIncrementUse in codeContinuation condition17for Loops• A command especially for count-controlled loops• Has initialization, continuation condition, and increment all in one command• The counter is called the for loop index• The loop index can then be used in the code as in the while loop• Next chart shows for loop to implement while loop code on previous chart18The for Loopint power = 2, max = 5;for ( int count = 0; count <= max; count = count + 1 ){result = pow( count,power );cout << count << "\t" << result << endl;}InitializationContinuation conditionIncrementUse in codeThe for loop March 9, 2006419for Loop Syntaxfor ( < initialize loop index >;< continuation condition >;< increment > ){// Statements in loop that// are executed repeatedly}20for loop operation• The for loop index is set to the value specified in the initialization statement• The continuation condition is checked– If the condition is false, the loop is not executed– If the condition is true, the loop is executed• At the end of the loop, the increment operation is applied and the looping process continues with a check of the continuation condition21for loop examples• What values of k will be included the following for loop?for (k = 1, k <= 6, k = k + 2)• What is the output from the following for loop code?for (k = 0, k <= 7, k = k + 3) {p = 3 * k;cout << p + k << endl;}1, 3, 50122422Combination Operators• Increment operations such as those in for loops (k = k + 2) occur often in programming• C++ has special combination operators to simplify such expressions• You do not have to use these operators, but you should understand them• For example: in place of count = count + a you can write count += a23Combination Operators IICombinationCoventionalcount %= a;count = count


View Full Document

CSUN COMP 106 - Count-controlled Loops

Download Count-controlled Loops
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Count-controlled Loops and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Count-controlled Loops 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?