Sunday, January 8, 2012

2.2.3. for

This command is mostly used to create parts of the program which must be repeated a certain number of times. Its format is

   for (startingValue; repetitionCondition; Increment)
     Statement;

So, to count from 1 to 10, we would have 1 as the starting value, <= 10 as the repetition condition, and the increment would be 1 a time. It is very common to use the letter "i" as a counter, when it comes to simple tasks, so the starting value would be "i = 1," the condition for the repetition would be "i <= 10" and the increment would be "i = i +1 "

    for (i=1; i<=10; i=i+1)
        ...

The command to increase the value of a variable ("i = i +1") can be written in the abbreviated form "i++", as discussed in more detail in the next chapter.

Usually, it is preferable to use more descriptive variable names, rather than "i". For example, a program to write the numbers 1 to 10 might be:

/*---------------------------*/
/*  C# Example #19:          */
/*  example19.cs             */
/*                           */
/*  Basic use of "for"       */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example19
{
  public static void Main()
  {

    int counter;

    for (counter=1; counter<=10; counter++)
      Console.Write("{0} ", counter);
 
  }
}

Suggested exercises:
·       Create a program to display the numbers 15 to 5, descending (hint: the counter will decrease on each pass, for example using i = i-1, which can be shortened i--).
·       Write a program to display the first eight even numbers (hint: on each pass we will have to increase the counter 2 units, or display the counter doubled).


In a "for" command, what we have called the "increment" does not really have to increment any variable, although that is its most common use. It is simply a command that is run when the repeated statements are completed, before checking again if the condition is still met.

So if we write the following line:

     for (counter=1; counter<=10; )

the value for the variable "counter" is never incremented, so the exit condition is never met, and the program never ends. This is an "endless loop".

An even more exaggerated case of endless loop is this one:

     for ( ; ; )

"For" loops can be nested (including one inside the other), so we could write the multiplication tables from 1 to 5 this way:

/*---------------------------*/
/*  C# Example #20:          */
/*  example20.cs             */
/*                           */
/*  nested "for"             */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example20
{
  public static void Main()
  {

    int table, number;

    for (table=1; table<=5; table++)

      for (number=1; number<=10; number++)

        Console.WriteLine("{0} times {1} is {2}", table, number,
          table*number);

  }
}


In these examples, there was a single sentence after "for". If we want to do several things, we just need set them as a block (compound statement) using curly brackets. For example, we can improve the previous example by leaving a blank line between each table and the next one:

/*---------------------------*/
/*  C# Example #21:          */
/*  example21.cs             */
/*                           */
/*  nested "for" (2)         */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example21
{
  public static void Main()
  {

    int table, number;

    for (table=1; table<=5; table++)
    {

      for (number=1; number<=10; number++)

        Console.WriteLine("{0} times {1} is {2}", table, number,
          table*number);

      Console.WriteLine();
    }

  }
}


The "counter" can also be a letter:

/*---------------------------*/
/*  C# Example #22:          */
/*  example22.cs             */
/*                           */
/*  "for" using "char"       */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example22
{
  public static void Main()
  {

    char letter;

    for (letter='a'; letter<='z'; letter++)
      Console.Write("{0} ", letter);
 
  }
}


In this case we started in "a" and ended up in "z", increasing by one.


If we want to count downwards, or two at at a time, or any other increment, we must change the increment block, and perhaps the completion block:

/*---------------------------*/
/*  C# Example #23:          */
/*  example23.cs             */
/*                           */
/*  "for" downwards          */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example23
{
  public static void Main()
  {

    char letter;

    for (letter='z'; letter>='a'; letter--)
      Console.Write("{0} ", letter);
 
  }
}

Note: We can even declare a new variable inside the "for", and that variable will disappear when the "for" ends:

     for (int i=1; i<=10; i++) ...



Suggested exercises:
Ø     Create a program to display the letters Z (upper case) to A (upper case, descending).
Ø     Create a program to write on screen the multiplication table of 5.
Ø     Create a program to write on screen the numbers from 1 to 50 that are multiples of 3 (hint: use the remainder of the division).

No comments:

Post a Comment