Sunday, January 29, 2012

3.5. The "Boolean" values

C# also includes a data type called "boolean" ("bool"), which can take two values: true or false:

bool found;
   
found = true;

This data type allows writing in a simpler way some conditions that may be complex. So we can make certain portions of our program more readable: not "if ((lives == 0) | | (time == 0) | | ((enemiesAlive == 0) & & (level == lastLevel)))" but simply " if (gameFinished) ... "

The variables "bool" also can be given value from the result of a comparison:

gameFinished = false;
gameFinished = (enemiesAlive ==0) && (level == lastLevel);
if (lives == 0) gameFinished = true;


We will use them from now on sources that use more complex conditions. An example to request a letter and say whether it is a vowel, a numerical figure, or other symbol, using "bool" variables might be:

/*---------------------------*/
/*  C# Example #32:          */
/*  example32.cs             */
/*                           */
/*  Conditions with if (8)   */
/*   bool variables          */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example32
{
  public static void Main()
  {
    char letter;
    bool isVowel, isDigit;

    Console.WriteLine("Enter a letter");
    letter = Convert.ToChar(Console.ReadLine());
   
    isDigit = (letter >= '0') && (letter <='9');

    isVowel = (letter == 'a') || (letter == 'e') || (letter == 'i') ||
      (letter == 'o') || (letter == 'u');
   
    if (isDigit)
      Console.WriteLine("It is a digit.");
    else if (isVowel)
        Console.WriteLine("It is a vowel.");
      else
        Console.WriteLine("It is a consonant or another symbol.");
  }
}

Suggested exercises:
·       Create a program that uses the conditional operator to give a boolean variable named "equal" the value "true" if the two numbers entered by the user are the same, or "false" if they are different.
·       Create a program that uses the conditional operator to give a boolean variable named "bothEven" the value "true" if two numbers entered by the user are the even, or "false" if any of them is odd.

No comments:

Post a Comment