Wednesday, December 28, 2011

2.1.3. Relational operators

We have seen that the ">" symbol is used to check whether a number is greater than another. The symbol for "less than" is also simple, but the others are a little less obvious, so let's see them:

Operator - Operation
  • < Less than
  • > Greater than
  • <= Less than or equal to
  • >= Greater than or equal to
  • == Equal to
  • != Not equal to (different from)

So an example to display if a number is NOT zero might be:

/*---------------------------*/
/* C# Example #7: */
/* example07.cs */
/* */
/* Conditions with if (3) */
/* */
/* Intro to C#, */
/* Nacho Cabanes */
/*---------------------------*/

using System;

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

Console.WriteLine("Enter a number");
number = Convert.ToInt32(Console.ReadLine());
if (number != 0)
Console.WriteLine("The number is not zero.");
}
}

Suggested exercises:
  • Create a program that multiplies two integer numbers as follows: ask the user a first integer. If the entered number is 0, the program should write on screen "The product of 0 by any number is 0". If the entered number is other than zero, the user is asked for a second number and the product of both is displayed.
  • Create a program that asks the user two integer numbers. If the second number is not zero, it must display the result of dividing the first by the second. Otherwise, if the second number is zero, it must print "Error: I can not divide by zero."

No comments:

Post a Comment