Slide 1Slide 2Slide 3Slide 4Slide 5Slide 6Slide 7Slide 8Slide 9Slide 10Slide 11Slide 12Slide 13Slide 14Slide 15Slide 16Slide 17Slide 18Slide 19Slide 20Slide 21Slide 22Slide 23Slide 24Slide 25Slide 26Slide 27COSC 181 – Foundations of Computer ProgrammingClass 1625.3 for Repetition Statement (Cont.)General form of the for statement•for ( initialization; loopContinuationCondition; increment ){ statement(s); }Can usually be rewritten as:initialization;while ( loopContinuationCondition ) { statement(s); increment; }If the control variable is declared in the initialization expressionIt will be unknown outside the for statement3Good Programming Practice 5.4 Using the final value in the condition of a while or for statement and using the <= relational operator will help avoid off-by-one errors. For a loop used to print the values 1 to 10, which is better? (Hint: one is an error) counter <= 10 •counter < 10•counter < 11 Many programmers prefer so-called zero-based counting, in which, to count 10 times through the loop, counter would be initialized to zero and the loop-continuation test would be counter < 10.4Good Programming Practice 5.5 Place only expressions involving the control variables in the initialization and increment sections of a for statement. Manipulations of other variables should appear either before the loop (if they should execute only once, like initialization statements) or in the loop body (if they should execute once per repetition, like incrementing or decrementing statements).55.3 for Repetition Statement (Cont.)The initialization and increment expressions can be comma-separated lists of expressionsThese commas are comma operatorsComma operator has the lowest precedence of all operatorsExpressions are evaluated from left to rightValue and type of entire list are value and type of the rightmost expressions65.4 Examples Using the for Statementfor statement examplesVary control variable from 1 to 100 in increments of 1•for ( int i = 1; i <= 100; i++ )Vary control variable from 100 to 1 in increments of -1•for ( int i = 100; i >= 1; i-- )Vary control variable from 7 to 77 in steps of 7•for ( int i = 7; i <= 77; i += 7 )Vary control variable from 20 to 2 in steps of -2•for ( int i = 20; i >= 2; i -= 2 )Vary control variable over the sequence: 2, 5, 8, 11, 14, 17, 20•for ( int i = 2; i <= 20; i += 3 )Vary control variable over the sequence: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0•for ( int i = 99; i >= 0; i -= 11 )71 // Fig. 5.5: f ig05_05.cpp2 / / Summing integers with the for statement.3 #inc lude <iostream>4 us ing std::cout;5 us ing std::endl;67 int main()8 {9 int total = 0; // initialize total1011 // total even integers from 2 through 2012 for ( int number = 2; number <= 20; number += 2 )13 total += number; 1415 cout << "Sum is " << total << endl; // display results16 return 0; // successful termination17 } // end mainSum is 110Outlinefig05_05.cpp(1 of 1)Vary number from 2 to 20 in steps of 2Add the current value of number to total85.4 Examples Using the for Statement (Cont.)Using a comma-separated list of expressionsLines 12-13 of Fig. 5.5 can be rewritten as for ( int number = 2; // initialization number <= 20; // loop continuation condition total += number, number += 2 ) // total and // increment ; // empty statement95.4 Examples Using the for Statement (Cont.)Standard library function std::powCalculates an exponentExample•pow( x, y )Calculates the value of x raised to the yth powerRequires header file <cmath>101 // Fig. 5.6: f ig05_06.cpp2 / / Compound in teres t calcu la t io ns with for .3 #inc lude <iostream>4 us ing std::cout;5 us ing std::endl;6 us ing std::fixed;78 #inc lude <iomanip>9 us ing std::setw; // enables program to set a field width 10 us ing std::setprecision;1112 #inc lude <cmath> // standard C++ math library 13 us ing std::pow; // enables program to use function pow1415 int main()16 {17 double amount; // amount on deposit at end of each year18 double principal = 1000.0; // initial amount before interest19 double rate = .05; // interest rate2021 // display headers22 cout << "Year" << setw( 21 ) << "Amount on deposit" << endl;2324 // set floating-point number format25 cout << fixed << setprecision( 2 );26Outlinefig05_06.cpp(1 of 2)C++ treats floating-point values as type double setw stream manipulator will set a field width standard library function pow (in header file <cmath>)Specify that the next value output should appear in a field width of 211127 // calculate amount on deposit for each of ten years 28 for ( int year = 1; year <= 10; year++ ) 29 { 30 // calculate new amount for specified year 31 amount = principal * pow( 1.0 + rate, year ); 32 33 // display the year and the amount 34 cout << setw( 4 ) << year << setw( 21 ) << amount << endl;35 } // end for 3637 return 0; // indicate successful termination38 } // end mainYear Amount on deposit 1 1050.00 2 1102.50 3 1157.63 4 1215.51 5 1276.28 6 1340.10 7 1407.10 8 1477.46 9 1551.33 10 1628.89Outlinefig05_06.cpp(2 of 2)Calculate amount within for statementUse the setw stream manipulator to set field width12Common Programming Error 5.7 In general, forgetting to include the appropriate header file when using standard library functions (e.g., <cmath> in a program that uses math library functions) is a compilation error.135.4 Examples Using the for Statement (Cont.)Formatting numeric outputStream manipulator setwSets field widthRight justified by defaultStream manipulator left to left-justifyStream manipulator right to right-justifyApplies only to the next output valueStream manipulators fixed and setprecisionSticky settingsRemain in effect until they are changed14Performance Tip 5.1 Avoid placing expressions whose values do not change inside loops—but, even if you do, many of
View Full Document