Wednesday, January 4, 2012

2.2.1. while

If we want to make a part of our program repeat while some condition is met, we can use the "while" statement. This command has two different formats, depending on if we check the condition at the beginning of the repetitive block or at the end.

In the first case, the syntax is

   while (condition)
     statement;

That is, the statement is repeated while the condition is met (true). If the condition is not met (false) from the very beginning, the statement is never executed. If we want to repeat more than one statement, we just need to group them using braces.

An example program to tell us if each entered number is positive or negative, and which stops when 0 is entered, might be:

/*---------------------------*/
/*  C# Example #16:          */
/*  example16.cs             */
/*                           */
/*  The "while" statement    */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example16
{
  public static void Main()
  {
    int number;

    Console.Write("Enter a number (0 to exit): ");
    number = Convert.ToInt32(Console.ReadLine());

    while (number != 0)
    {

      if (number > 0) Console.WriteLine("It's positive");
        else Console.WriteLine("It's negative");

      Console.WriteLine("Enter another number (0 to exit): ");
      number = Convert.ToInt32(Console.ReadLine());

    }

  }
}


In this example, if the user enters 0, the condition is false and the program ends immediately.

Suggested exercises:
·       Create a program that asks the user for a numeric password. The program will end when the used enters the number 1111, and ask again as many times as necessary if he enters a wrong password.
·       Write a program to write on the screen the numbers 1 to 10, using "while".
·       Create a program to display on the screen the even numbers from 26 to 10 (downwards), using "while".
·       Create a program to calculate how many digits has a positive integer (hint: it can be done by dividing by 10 several times).
·       Create the flowchart and the C# version of a program that gives the user three chances to guess a number from 1 to 10.

No comments:

Post a Comment