Selection and Repetition
5.2 Nested ifs and the switch Statement 125
5.3.3 The for Statement
The for statement provides a powerful iteration capability. It works well when we know the number of repetitions. Technically we could use a while
statement instead of a for statement in these cases, but it is much more convenient to say
Do this calculation 10 times.
than it is to write
Declare and initialize a count variable to zero.
while (count < 10) { doSomething;
count ++;
}
Theforstatement performs the same steps but packages them more conve-niently, following the pattern
for (initialize; test; update) for_body_statement
where for_body_statementcan be a simple statement or a block. Figure 5.14 shows the flow diagram for the forstatement. The code in Figure 5.15 uses a forstatement to add the numbers from one to four. The initialize part declares and initializes a variable,i, called the index or counter, which will count the repetitions.
The test expression,i <= 4, checks whether we need more repetitions. C#
will execute the statementsum += i, of theforloop body, if the test condition
5.3 Repetition 129
Figure 5.14 Flow diagram for the forstatement.
true false Test?
Initialize
for_statement
Update
Figure 5.15 A forstatement for the sum 1+2+3+4.
int sum = 0;
for (int i = 1; i <= 4; i++) sum += i;
is true, in this case if the count,i, is less than or equal to four. The loop ter-minates when the test condition becomes false, in this case wheniis greater than four. The update expression, i++ in this example, increments the count,i, by one. C# executes the update expression, after executing thefor
loop body. Figure 5.16 traces the execution of theforloop of Figure 5.15.
The update expression can be more general than the increment in Figure 5.15. In Figure 5.17, we find the sum of the positive odd numbers less than 10.
In each iteration, we add two to the index variable,i, which gets the values 1, 3, 5, 7, and 9, each of which is added to sum, whose final value is 25.
Normally the index variable increases at each iteration, as in the code of Figures 5.15 and 5.17. However, we can initialize the index to its highest value and decrement it at each iteration, as in Figure 5.18, which also com-putes the sum of the first four positive integers.
Figure 5.18 A forstatement forthe sum 4+3+2+1.
int sum = 0;
for (int i = 4; i >= 1; i--) sum += i;
Figure 5.16 Trace of execution of the forloop of Figure 5.15.
initialize i = 1
Figure 5.17 A forstatement forthe sum 1+3+5+7+9.
int sum = 0;
for (int i = 1; i < 10; i += 2) sum += i;
Now that we have seen how to write a forstatement, we will use it in Exam-ple5-3 to find how much our money will grow in a bank account. The account earns interest at a certain rate over a specified time, assuming that interest is compounded yearly. (At the end of the year, the interest due for that year is added to the principal.) Example5-3 uses a ComboBoxfor the user to select an interest rate, a TextBox to enter the initial account balance, a
NumericUpDownto select the number of years, and a Buttonto find the accu-mulated amount. Three Labelcontrols describe the purpose of the other controls. Figure 5.19 shows the form of Example5-3.
We use Propertieswindows to configure each control. We click on the Form
in the design view and click on the View, Properties menu item to show the
5.3 Repetition 131
Figure 5.19 The form of Example5-3.
Figure 5.20 Choosing a background color.
Properties window for the Form. We change the Text property to Find growth, which will display in the title at the top of the form. We change the
BackColorto orange by choosing a color from the grid in the Customtab that pops up when we click the button that appears at the right of the BackColor
property entry. Figure 5.20 shows the color grid that appears.
We configure the ComboBoxwith a list of interest rates. Clicking the Items
property shows a button that we click to pop up the String Collection Edi-torwindow shown in Figure 5.21, in which we enter four interest rates, 2.0, 3.2, 4.5, and 5.1. We change the (Name)of this ComboBoxto selectRateand its
Text property to the empty string. The Label below it will have its Text
property set to Interest rate.
Figure 5.22 Displaying the accumulated amount.
Figure 5.21 Entering the interest rate choices.
We change the Textproperty of the TextBoxto the empty string so it will be blank initially. We change its (Name) property to enterAmount. The Label
below will have its Textproperty set to Deposit amount.
We set the Textof the Buttonto Growth and change its (Name)to showResult. We change the (Name)of the NumericUpDownto selectYears, and change the
Textof the Labelbelow it to Years.
To develop a solution, let us start with a simple case, $1000 at 5% for three years. For each year, we have to find the interest earned and add it to the account balance, as the following table shows.
Year Interest New Balance
1 1000 * .05 = 50 1000 + 50 = 1050
2 1050 * .05 = 52.50 1050 + 52.50 = 1102.50
3 1102.50 * .05 = 55.13 1102.50 + 55.13 = 1157.63
From this example, we see that each year we find the interest and add it to the balance to get the new balance. We will put these two steps in the body of our forstatement.
The user chooses an interest rate from a ComboBox, enters an amount to deposit in a TextBox, and scrolls a NumericUpDownto specify the duration of the account. When the user clicks the Growth button, its event handler computes the amount of money in the account when it matures and dis-plays it in a MessageBoxas shown in Figure 5.22.
5.3 Repetition 133
Figure 5.23 Syntax for the dostatement.
do
statement while (condition) ;
To display the template for the event handler for the Button, we double-click on it in the design view. The event-handling code is
private void showResult_Click
In the event handler we first place the user entries in variables. We con-vert the interest rate to adoubleand divide by 100 so that 3.2% becomes 0.032. The Valuefor the years in the NumericUpDown has type decimal. We convert the deposit amount to typedoubleand initialize a result variable with this value.
Theforloop computes the interest for each year and adds it to the result. A
MessageBoxdisplays the result in currency format.