Varying the For Loop’s Behavior

Several variations of this basic loop are used for different kinds of counting situations. You can set up for loops that skip over numbers, count by two, or count backwards. The basic design of the for statement is the same, but you can change the way the three parts of the for loop are written to change the way the loop acts.

The Fancy Beans Program

The Fancy Beans program demonstrates a few variations on the theme of the basic for loop. Take a look at the output of this program in Figure 3.6, then I’ll show you how the code works.

Figure 3.6. This bean counter can count by fives, backwards, and pulls the words out of a sentence one at a time.


Take a look at the code for the fancier bean counter, and I’ll explain the details:

using System;

namespace fancyBean
{
   /// <summary>
   /// Demonstrates a number of variations of the for loop
   /// Andy Harris, 11/29/01
   /// </summary>
   class fancyBean
   {
     static void Main(string[] args)
     {
       int i;
       string sentence = "Count those fancy beans"; 
       //counting by fives
       Console.WriteLine("Counting by fives:");
       for(i = 0; i <= 100; i += 5){
         Console.Write(i + "	");
       } // end for loop
       Console.WriteLine();
       Console.WriteLine();

       //count backwards
       Console.WriteLine("Counting backwards:");
       for(i = 10; i > 0; i--){
         Console.Write(i + "	");
       } // end for loop
       Console.WriteLine();
       Console.WriteLine();

       //demonstrate foreach loop
       Console.WriteLine("Getting words in a sentence");
       foreach (string word in sentence.Split()){
         Console.WriteLine(word);
       } // end foreach
       Console.WriteLine();
       Console.WriteLine();

       Console.WriteLine("Please press enter key to continue");
       Console.ReadLine();

     } // end main
   } // end class
 } // end namespace

As you can see, this program has three for loops. Each for loop demonstrates a different variation of the basic for loop.

Skipping Numbers

The first loop in this program counts by 5’s to 100 by slightly changing the parts of the for loop statement. In this program, I use the lowercase i as a counting variable.

NOTE

IN THE REAL WORLD

Although I have told you in other places that 1-character variable names are not a good idea, there is a grand tradition regarding the use of i as a for loop sentry variable, especially if that variable will not be used for anything else. The use of i in this situation goes all the way back to the earliest versions of FORTRAN, where integer variables had to start with the letters i, j, and so on. Even programmers who have never written any significant code in FORTRAN (like me) follow the tradition and frequently use i as a generic counting variable. For such a young endeavor, computer programming has a rich history.

The key line for making the program count to 100 by 5’s is

for(i = 0; i <= 100; i += 5){

It means “start i at 0, keep going as long as i is less than or equal to 100, and add 5 to i each time through the loop.” The += syntax is similar to the ++ syntax but allows you to add any value to a variable. Therefore,

i += 5;

is the same as

i = i + 5;

but the first version is easier to type. Programmers are lazy, so they prefer the more concise syntax.

Counting Backwards

When you understand the basic mechanics of the for loop, it isn’t much of a surprise that you can make a loop go backwards. However, you must be careful because a couple things have to change to make a backwards loop. The line that looks like

for(i = 10; i > 0; i--){

handles the backwards behavior. Notice that I had to start i with a value larger than 0 and that my condition checks whether i is larger than 0. The i-- behavior decrements i, so i-- means the same as i = i - 1.

Using a Foreach Loop to Break Up a Sentence

The for loop has one more variation that is useful in certain circumstances. The foreach loop will be valuable in the Pig Latin program, so I’ll show it to you now, even though its full value will be apparent only after you learn arrays in Chapter 8, “Arrays: The Soccer Game.” The foreach loop extracts specific elements from a group. The line in the Fancy Beans program that uses the foreach loop looks like this:

foreach (string word in sentence.Split()){

In a foreach loop, you can use any kind of variable as the sentinel variable, but you must get that variable from a group. The Split() method of a string automatically splits a phrase into a group of words, so this foreach loop repeats one time for each word in a phrase. Each time through the loop, the word variable contains the next word in the sentence. Inside the loop, you can see that I use WriteLine() to print each word on a separate line in the output. When you need to break a phrase or sentence into words, use the foreach loop.

This description of the foreach loop might be unsatisfactory because the foreach loop is dependent on arrays, which you will learn about in Chapter 8, Arrays: The Soccer Game.” You will also see more about the use of the foreach loop in that chapter. In the meantime, simply remember that the foreach code combined with the string.Split() method makes a loop that features each word in a sentence. You will be able to use this feature even if you don’t completely understand it.

..................Content has been hidden....................

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