2. When the app executes, another compiler (known as the just-in-time compiler
6.4 Examples Using the for Statement
Apps frequently display the control variable value or use it in calculations in the loop body, but this use is not required. The control variable is commonly used to control rep- etition without being mentioned in the body of thefor.
Figure 6.4 shows the activity diagram of theforstatement in Fig. 6.2. The diagram makes it clear that initialization occursonly oncebefore the loop-continuation test is eval- uated the first time, and that incrementing occurseachtime through the loop after the body statement executes.
6.4 Examples Using the for Statement
The following examples show techniques for varying the control variable in aforstate- ment. In each case, we write the appropriateforheader. Note the change in the relational operator for loops that decrement the control variable.
a) Vary the control variable from1to100in increments of1.
b) Vary the control variable from100to1in decrements of1.
c) Vary the control variable from7to77in increments of7. Error-Prevention Tip 6.4
Although the value of the control variable can be changed in the body of aforloop, avoid doing so, because this can lead to subtle errors.
Fig. 6.4 | UML activity diagram for theforstatement in Fig. 6.2.
for ( int i = 1; i <= 100; ++i )
for ( int i = 100; i >= 1; --i )
for ( int i = 7; i <= 77; i += 7 ) Determine whether
looping should
continue Console.Write( “{0} ”, counter );
[counter > 10]
[counter <= 10]
int counter = 1
++counter Display the
counter value Initialize
control variable
Increment the control variable
d) Vary the control variable from20to2in decrements of2.
e) Vary the control variable over the sequence2,5,8,11,14,17,20.
f) Vary the control variable over the sequence99,88,77,66,55,44,33,22,11,0.
App: Summing the Even Integers from 2 to 20
We now consider two sample apps that demonstrate simple uses of for. The app in Fig. 6.5 uses aforstatement to sum the even integers from 2 to 20 and store the result in anintvariable calledtotal.
Theinitializationandincrementexpressions can becomma-separated liststhat enable you to usemultipleinitialization expressions ormultipleincrement expressions. For example, you could merge the body of theforstatement in lines 12–13 of Fig. 6.5 into the increment por- tion of theforheader by using a comma as follows:
We prefernotcomplicatingforheaders in this manner.
for ( int i = 20; i >= 2; i -= 2 )
for ( int i = 2; i <= 20; i += 3 )
for ( int i = 99; i >= 0; i -= 11 )
Common Programming Error 6.2
Not using the proper relational operator in the loop-continuation condition of a loop that counts downward (e.g., usingi <= 1instead ofi >= 1in a loop counting down to 1) is a logic error.
1 // Fig. 6.5: Sum.cs
2 // Summing integers with the for statement.
3 using System;
4
5 public class Sum 6 {
7 public static void Main( string[] args )
8 {
9 10
11 // total even integers from 2 through 20 12
13 14
15 Console.WriteLine( "Sum is {0}", total ); // display results 16 } // end Main
17 } // end class Sum
Sum is 110
Fig. 6.5 | Summing integers with theforstatement.
for ( int number = 2; number <= 20; total += number, number += 2 )
; // empty statement
int total = 0; // initialize total
for ( int number = 2; number <= 20; number += 2 ) total += number;
6.4 Examples Using theforStatement 197
App: Compound-Interest Calculations
The next app uses theforstatement to compute compound interest. Consider the follow- ing problem:
A person invests $1,000 in a savings account yielding 5% interest, compounded yearly. Assuming that all the interest is left on deposit, calculate and display the amount of money in the account at the end of each year for 10 years. Use the following formula to determine the amounts:
a = p(1 +r)n where
pis the original amount invested (i.e., the principal) ris the annual interest rate (e.g., use 0.05 for 5%) nis the number of years
ais the amount on deposit at the end of thenth year.
This problem involves a loop that performs the indicated calculation for each of the 10 years the money remains on deposit. The solution is the app shown in Fig. 6.6. Lines 9–11 in methodMaindeclaredecimalvariablesamountandprincipal, anddoublevari- ablerate. Lines 10–11 also initializeprincipalto1000(i.e., $1000.00) andrateto0.05. C# treats real-number constants like0.05 as type double. Similarly, C# treats whole- number constants like7and1000as typeint. Whenprincipalis initialized to1000, the value1000of typeintispromotedto adecimaltypeimplicitly—no cast is required.
1 // Fig. 6.6: Interest.cs
2 // Compound-interest calculations with for.
3 using System;
4
5 public class Interest 6 {
7 public static void Main( string[] args )
8 {
9 decimal amount; // amount on deposit at end of each year 10 decimal principal = 1000; // initial amount before interest 11 double rate = 0.05; // interest rate
12
13 // display headers
14 Console.WriteLine( "Year{0,20}", "Amount on deposit" );
15 16 17 18 19 20 21 22 23 24 25
26 } // end Main
27 } // end class Interest
Fig. 6.6 | Compound-interest calculations withfor. (Part 1 of 2.)
// calculate amount on deposit for each of ten years for ( int year = 1; year <= 10; ++year )
{
// calculate new amount for specified year amount = principal *
( ( decimal ) Math.Pow( 1.0 + rate, year ) );
// display the year and the amount
Console.WriteLine( "{0,4}{1,20:C}", year, amount );
} // end for
Line 14 outputs the headers for the app’s two columns of output. The first column displays the year, and the second displays the amount on deposit at the end of that year.
We use the format item{0,20}to output thestring "Amount on deposit". The integer
20after the comma indicates that the value output should be displayed with afield width of 20—that is,WriteLinedisplays the value with at least 20 character positions. If the value to be output isless than20 character positions wide (17 characters in this example), the value isright justifiedin the field by default (in this case the value is preceded by three blanks). If theyearvalue to be output weremorethan four character positions wide, the field width would beextended to the rightto accommodate the entire value—this would push theamountfield to the right, upsetting the neat columns of our tabular output. To indicate that output should beleft justified, simply use anegativefield width.
Theforstatement (lines 17–25) executes its body 10 times, varying control variable
yearfrom1to 10in increments of1. This loop terminates when control variableyear becomes11. (yearcorresponds tonin the problem statement.)
Classes provide methods that perform common tasks on objects. In fact, most methods must be called on a specific object. For example, to output a greeting in Fig. 4.2, we called methodDisplayMessageon themyGradeBookobject. Many classes also provide methods that perform common tasks and cannot be called on objects—theymustbe called using a class name. Such methods are calledstaticmethods. For example, C# does not include an exponentiation operator, so the designers of C#’sMathclass definedstaticmethodPow for raising a value to a power. You can call astaticmethod by specifying the class name followed by the member access (.) operator and the method name, as in
ConsolemethodsWriteandWriteLinearestaticmethods. In Chapter 7, you’ll learn how to implementstaticmethods in your own classes.
We usestaticmethodPowof classMathto perform the compound interest calcula- tion in Fig. 6.6.Math.Pow(x,y)calculates the value of xraised to the yth power. The method receives twodoublearguments and returns adoublevalue. Lines 20–21 perform the calculationa=p(1 +r)n, whereais theamount,pis theprincipal,ris therateand nis theyear. Notice that, in this calculation, we need to multiply adecimalvalue (prin-
cipal) by adoublevalue (the return value ofMath.Pow). C# will not implicitly convert
doubleto adecimaltype, or vice versa, because of thepossible loss of informationin either conversion, so line 21 contains a (decimal) cast operator that explicitly converts the
doublereturn value ofMath.Powto adecimal.
Year Amount on deposit
1 $1,050.00
2 $1,102.50
3 $1,157.63
4 $1,215.51
5 $1,276.28
6 $1,340.10
7 $1,407.10
8 $1,477.46
9 $1,551.33
10 $1,628.89
ClassName.MethodName( arguments )
Fig. 6.6 | Compound-interest calculations withfor. (Part 2 of 2.)