We can specify what should happen if the condition is not met, using the "else" command:
/*---------------------------*/
/* C# Example #8: */
/* example08.cs */
/* */
/* Conditions with if (4) */
/* */
/* Intro to C#, */
/* Nacho Cabanes */
/*---------------------------*/
using System;
public class Example08
{
public static void Main()
{
int number;
Console.WriteLine("Enter a number");
number = Convert.ToInt32(Console.ReadLine());
if (number > 0)
Console.WriteLine("The number is positive.");
else
Console.WriteLine("The number is zero or negative.");
}
}
We could try to avoid using "else" if we place an "if" after another, like this:
/*---------------------------*/
/* C# Example #9: */
/* example09.cs */
/* */
/* Conditions with if (5) */
/* */
/* Intro to C#, */
/* Nacho Cabanes */
/*---------------------------*/
using System;
public class Example09
{
public static void Main()
{
int number;
Console.WriteLine("Enter a number");
number = Convert.ToInt32(Console.ReadLine());
if (number > 0)
Console.WriteLine("The number is positive.");
if (number <= 0)
Console.WriteLine("The number is zero or negative.");
}
}
But the behavior is not the same: in the first case (Example 8) the computer will see if the value is positive, and if it is not, it proceed to the second statement, but if it was positive, the program finishes. In the second case (Example 9), even if the number is positive, the program checks the other condition, in order to see if the number is negative or zero, so the second program is slightly slower.
We can chain several "if" statements, using "else" to mean "if this condition is not met, let's check to this other":
/*---------------------------*/
/* C# Example #10: */
/* example10.cs */
/* */
/* Conditions with if (6) */
/* */
/* Intro to C#, */
/* Nacho Cabanes */
/*---------------------------*/
using System;
public class Example10
{
public static void Main()
{
int number;
Console.WriteLine("Enter a number");
number = Convert.ToInt32(Console.ReadLine());
if (number > 0)
Console.WriteLine("The number is positive.");
else
if (number < 0)
Console.WriteLine("The number is negative.");
else
Console.WriteLine("The number is zero.");
}
}
Suggested exercise:
· Improve the solution for the exercises in the previous paragraph, using "else".
No comments:
Post a Comment