6.5 App: Summing Even Integers

We now consider a sample app that demonstrates a simple use of for. The app in Fig. 6.5 uses a for statement to sum the even integers from 2 to 20 and store the result in an int variable called total. Each iteration of the loop (lines 12–15) adds control variable number’s value to variable total.

Fig. 6.5 Summing integers with the for statement.

Alternate View

  1    // Fig. 6.5: Sum.cs
  2    // Summing integers with the for statement.
  3    using System;
  4
  5    class Sum
  6    {
  7       static void Main()
  8       {
  9          int total = 0; // initialize total
 10
 11              // total even integers from 2 through 20
 12              for (int number = 2; number <= 20; number += 2)
 13              {                                              
 14                 total += number;                            
 15              }                                              
 16
 17              Console.WriteLine($"Sum is {total}"); // display results
 18         }
 19    }

Sum is 110

The initialization and increment expressions can be comma-separated lists that enable you to use multiple initialization expressions or multiple increment expressions. For example, although this is discouraged, you could merge the for’s body statement (line 14) into the increment portion of the for header by using a comma as follows:


total += number, number += 2
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset