Unformatted text preview:

Introduction to looping March 7, 20061Introduction to LoopingIntroduction to LoopingLarry CarettoComputer Science 106Computing in Engineering and ScienceMarch 7, 20062Outline• Review last topic– Choice (if) statements• Looping– Basic idea for looping– while and do while statements– Practice writing loops3Review Choice (if statements)• Three structures if, if-else, and if-else-if• Based on statement if (<condition>)• Condition used relational operators (<, >, <=, >=, ==, !=) and logical operators not(!) and(&&) or(||)• Condition evaluates to true or false• In if-else and if-else-if only one block of code is executed• Nested if blocks4Review Type bool Variables• Type bool variables have two possible values: true and false• Can be used to hold result of expressions that give these values• leapYear = year % 4 == 0 && ( year % 100 != 0 || year % 400 == 0 )• Test bool variables in if statements and use with logical operatorsif ( leapYear && month == 2 ) days = 29;5Review DeMorgan’s Laws• Have two bool expressions, a and b, that can have values of true or false• Combinations of conditions for a and b satisfy both of the following• !(a && b) = !a || !b• !(a || b) = !a && !b• Proved these using truth table• Application to data validation follows6Review Data Validation• Apply DeMorgan’s Law to ValidationbadData = x < Min || x > Max;goodData = x >= Min && x <= Max;goodData = !badData;goodData = !(x < Min || x > Max);!(a || b ) = !a && !bgoodData = !(x < Min) && !(x>Max)goodData = x >= Min && x <= MaxIntroduction to looping March 7, 200627Review switch Statement• Alternative to if–else–if • Operates on equality condition only• All statements after first match is found are executedchar c;switch ( c ){case 'A':capa = capa + 1;break;case 'a':smla = smla + 1;break;default:nota = nota + 1;}8Looping• Executes portions of code repeatedly• Some data values change, but basic operations are the same– Repeated calculations for multiple data sets– Processing student records– Calculating company payroll– Trial and error calculations– Repeat entire program at user option• Example of last item in exercise one9Choice After LoopsYesNoIs condition true?Loop blockNext statementStatements in loop block must change condition10Exercise One Task Three Codechar yesNo;do{ // Repeated Statements herecout << "\n\nDo you want" << "a new case Y[es]/N[o]? ";cin >> yesNo;}while ( (yesNo == 'Y') ||(yesNo == 'y’) );11Choice Before LoopsYesNoIs condition true?Loop blockNext statementStatements in loop block must change condition12Test Before Loop Codechar yesNo = 'y’;while ( (yesNo == 'Y') ||(yesNo == 'y’) ){// Repeated Statements herecout << "\n\nDo you want" << "a new case Y[es]/N[o]? ";cin >> yesNo;}No semi-colon hereIntroduction to looping March 7, 2006313Basic Loop Structureswhile ( <condition>){// Repeated statements }do {// Repeated statements } while ( <condition>);No semicolon in whileSemi-colon in do while14Example• Repeatedly input a type double variable x from the keyboard, compute and print its natural logarithm using the log(x) function until the user enters zero or a negative numberdo {cout << “\nEnter x (x <= 0 exits loop): “;cin >> x;cout << “ln(“ << x << “) = “ << log(x);} while ( x > 0 );What happens in log(x) when user enters x <= 0?15Example II• Modify code on previous page to avoid error when x <= 0do {cout << “\nEnter x (x <= 0 exits loop): “;cin >> x;if ( x > 0 ) {cout << “ln(“ << x << “) = “ << log(x);}}while ( x > 0 );16Example III• Rewrite code using a test before loopcout << “Enter x (x <= 0 exits loop): “;cin >> x;while ( x > 0 ){cout << “ln(“ << x << “) = “ << log(x);cout << “\nEnter x (x <= 0 exits loop): “;cin >> x;}17Example IV• Either of the last two versions of the code work equally well• Note role of variable x– Although it is a single variable its value changes each time through the loop– This is typical of looping codes – the same variables are used, but their values change each time through the loop18Applications of Looping• Looping can reduce the code required for repeated calculations• Looping can provide more general application of a code– Without loops write code to handle a specific number of items– With loops, repeat operations for as many items as desired– Look at exercise four as an exampleIntroduction to looping March 7, 2006419Exercise Four Task Three CodeinFile >> x1 >> y1 >> z1 >> eT1>> x2 >> y2 >> z2 >> eT2>> x3 >> y3 >> z3 >> eT3>> x4 >> y4 >> z4 >> eT4;r1 = sqrt( x1 * x1 + y1 * y1 + z1 * z1 );r2 = sqrt( x2 * x2 + y2 * y2 + z2 * z2 );r3 = sqrt( x3 * x3 + y3 * y3 + z3 * z3 );r4 = sqrt( x4 * x4 + y4 * y4 + z4 * z4 );T1 = c0 + c1 * eT1 + c2 * eT1 * eT1;T2 = c0 + c1 * eT2 + c2 * eT2 * eT2;T3 = c0 + c1 * eT3 + c2 * eT3 * eT3;20Exercise Four Task Three CodeT3 = c0 + c1 * eT3 + c2 * eT3 * eT3;T4 = c0 + c1 * eT4 + c2 * eT4 * eT4;outFile << setprecision(3) << setw(10) << x1<< setw(13) << y1 << setw(13) << z1<< setw(13) << r1 << setprecision(2) << setw(13)<< eT1 << setprecision(1)<< setw(14) << T1 << endl;// Three more outFile statements for data// sets 2, 3, and 4 21Looping Code• What does code on last two charts do?– Reads in four sets of values for x, y, z, eT– Computes r and T for each input set– Produces output for each input set• Same calculations for each data set• If we had a different number of data sets we would have to rewrite code• Code like this can be done in loops22Loop PseudocodeSet counter to zeroRepeat the followingRead input for one case from fileDo calculations for that caseWrite output for case to fileIncrement counterWhile counter is less than the number of data sets (four in this example)23Previous Code in a Loopcounter = 0do{inFile << x << y << z << eT;r = sqrt( x * x + y * y + z * z );T = c0 + c1 * eT + c2 * eT * eT;24Previous Code in a LoopoutFile << setprecision(3)<< setw(10) << x<< setw(13) << y<< setw(13) << z<< setw(13) << r << setprecision(2)<< setw(13) << eT<< setprecision(1)<< setw(14) << T << endl;counter = counter + 1} while ( counter < 4 );Introduction to looping March 7, 2006525Effect of Looping on Variables• Look at the following code in the loopinFile x << y << z << eT;r = sqrt( x * x + y * y + z * z );T = c0 + c1 * eT + c2 * eT * eT;• x, y, z, r, eT and T refer to current data set and are overwritten with new data each time through loop26Is Count Correct?• Watch out for


View Full Document

CSUN COMP 106 - Introduction to Looping

Download Introduction to Looping
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 Introduction to Looping 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 Introduction to Looping 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?