Introduction to Conditional Statements
Introduction to Conditional Statements
Fundamentals of Conditional Statements
If a Condition is Other Than True
Condider the following code:
using System;
public enum HouseType
{
Unknown,
SingleFamily,
Townhouse,
Condominium
}
public class Exercise
{
static int Main()
{
var type = HouseType.Unknown;
var choice = 0;
Console.WriteLine("Enter the type of house you want to purchase");
Console.WriteLine("1. Single Family");
Console.WriteLine("2. Townhouse");
Console.WriteLine("3. Condominium");
Console.Write("You Choice? ");
choice = int.Parse(Console.ReadLine());
if (choice == 1)
type = HouseType.SingleFamily;
if (choice == 2)
type = HouseType.Townhouse;
if (choice == 3)
type = HouseType.Condominium;
Console.WriteLine("\nDesired House Type: {0}", type);
if (type == HouseType.SingleFamily)
Console.WriteLine("\nDesired House Matched");
return 0;
}
}
If you use an if condition to perform an operation and if the result is true, we saw that you could execute the statement. As we saw in the previous section, any other result would be ignored. To address an alternative to an if condition, you can use the else condition. The formula to follow is:
if(Condition) Statement1; else Statement2;
Once again, the Condition can be a Boolean operation like those we studied in the previous lesson. If the Condition is true, then the compiler would execute Statement1. If the Condition is false, then the compiler would execute Statement2. Here is an example:
using System;
public enum HouseType
{
Unknown,
SingleFamily,
Townhouse,
Condominium
}
public class Program
{
static int Main()
{
var type = HouseType.Unknown;
var choice = 0;
Console.WriteLine("Enter the type of house you want to purchase");
Console.WriteLine("1. Single Family");
Console.WriteLine("2. Townhouse");
Console.WriteLine("3. Condominium");
Console.Write("You Choice? ");
choice = int.Parse(Console.ReadLine());
if (choice == 1)
type = HouseType.SingleFamily;
if (choice == 2)
type = HouseType.Townhouse;
if (choice == 3)
type = HouseType.Condominium;
Console.WriteLine("\nDesired House Type: {0}", type);
if (type == HouseType.SingleFamily)
Console.WriteLine("Desired House Matched");
else
Console.WriteLine("No House Desired");
return 0;
}
}
Here is an example of running the program:
Enter the type of house you want to purchase 1. Single Family 2. Townhouse 3. Condominium You Choice? 1 Desired House Type: SingleFamily Desired House Matched Press any key to continue . . .
Here is another example of running the program:
Enter the type of house you want to purchase 1. Single Family 2. Townhouse 3. Condominium You Choice? 2 Desired House Type: Townhouse No House Desired Press any key to continue . . .
Practical Learning: Using the if...else Condition
namespace Chemistry03 { public class Element { public string Symbol; public string ElementName; public int AtomicNumber; public double AtomicWeight; public Element(int number) { AtomicNumber = number; } public Element(string symbol) { Symbol = symbol; } public Element(int number, string symbol, string name, double mass) { Symbol = symbol; ElementName = name; AtomicWeight = mass; AtomicNumber = number; } } }
using static System.Console;
namespace Chemistry03
{
public class Chemistry
{
private static void Describe(Element e)
{
WriteLine("Chemistry - " + e.ElementName);
WriteLine("------------------------");
WriteLine("Symbol: " + e.Symbol);
WriteLine("Element Name: " + e.ElementName);
WriteLine("Atomic Number: " + e.AtomicNumber);
WriteLine("Atomic Weight: " + e.AtomicWeight);
}
public static int Main()
{
Element elm = null;
Element h = new Element(1, "H", "Hydrogen", 1.008);
Element he = new Element(2, "He", "Helium", 4.002602);
Element li = new Element(3, "Li", "Lithium", 6.94);
Element be = new Element(4, "Be", "Beryllium", 9.0121831);
Element b = new Element(5, "B", "Boron", 10.81);
Element c = new Element(name: "Carbon", mass: 12.011, symbol: "C", number: 6);
Element n = new Element(number: 7, symbol: "N", name: "Nitrogen", mass: 14.007);
Element o = new Element(number: 8, symbol: "O", name: "Oxygen", mass: 15.999);
Element f = new Element(number: 9, symbol: "F", name: "Fluorine", mass: 15.999);
Element ne = new Element(number: 10, symbol: "Ne", name: "Neon", mass: 20.1797);
Element na = new Element(11, "Na", "Sodium", mass: 22.98976928);
Element mg = new Element(12, "Mg", "Magnesium", 24.305);
WriteLine("Chemistry - Periodic Table");
WriteLine("------------------------------------------------");
Write("In the periodic table, what it the atomic number for neon (1-12): ");
int answer = int.Parse(ReadLine());
elm = new Element(answer);
Clear();
WriteLine("Your answer: {0}", answer);
WriteLine("------------------------------------------------");
if (answer == 10)
{
WriteLine("Good Answer");
Describe(ne);
}
else
WriteLine("Wrong Answer: Please review your periodic table");
WriteLine("================================================");
return 0;
}
}
}
Chemistry - Period Table ------------------------------------------------ In the periodic table, what it the atomic number for neon (1-12):
Chemistry - Periodic Table ------------------------------------------------ In the periodic table, what it the atomic number for neon (1-12): 10
Your answer: 10 ------------------------------------------------ Good Answer Chemistry - Neon ------------------------ Symbol: Ne Element Name: Neon Atomic Number: 10 Atomic Weight: 20.1797 ================================================ Press any key to continue . . .
If you have a condition that can be checked as an if situation with one alternate else, you can use the ternary operator that is a combination of ? and :. Its formula is:
Condition ? Statement1 : Statement2;
The compiler would first test the Condition. If the Condition is true, then it would execute Statement1, otherwise it would execute Statement2. When you request two numbers from the user and would like to compare them, the following program would do find out which one of both numbers is higher. The comparison is performed using the conditional operator:
using static System.Console;
public class Exercise
{
static int Main()
{
var Number1 = 0;
var Number2 = 0;
var Maximum = 0;
var Num1 = "";
var Num2 = "";
Write("Enter first numbers: ");
Num1 = ReadLine();
Write("Enter second numbers: ");
Num2 = ReadLine();
Number1 = int.Parse(Num1);
Number2 = int.Parse(Num2);
Maximum = (Number1 < Number2) ? Number2 : Number1;
Write("\nThe maximum of ");
Write(Number1);
Write(" and ");
Write(Number2);
Write(" is ");
WriteLine(Maximum);
return 0;
}
}
Here is an example of running the program:
Enter first numbers: 244 Enter second numbers: 68 The maximum of 244 and 68 is 244
If you use an if...else conditional statement, you can process only two statements. In some cases, you may deal with more than two conditions. In this case, you can use an if...else if condition. Its formula is:
if(Condition1) Statement1; else if(Condition2) Statement2;
The compiler would first check Condition1. If Condition1 is true, then Statement1 would be executed. If Condition1 is false, then the compiler would check Condition2. If Condition2 is true, then the compiler would execute Statement2. Any other result would be ignored. Here is an example:
using static System.Console; public enum HouseType { Unknown, SingleFamily, Townhouse, Condominium } public class Exercise { static int Main() { var type = HouseType.Unknown; var choice = 0; var garage = ""; WriteLine("Enter the type of house you want to purchase"); WriteLine("1. Single Family"); WriteLine("2. Townhouse"); WriteLine("3. Condominium"); Write("You Choice? "); choice = int.Parse(ReadLine()); if (choice == 1) type = HouseType.SingleFamily; else if (choice == 2) type = HouseType.Townhouse; Write("Does the house have an indoor garage (1=Yes/0=No)? "); var answer = int.Parse(ReadLine()); if (answer == 1) garage = "Yes"; else garage = "No"; WriteLine("\nDesired House Type: {0}", type); WriteLine("Has indoor garage? {0}", garage); return 0; } }
Here is an example of running the program:
Enter the type of house you want to purchase 1. Single Family 2. Townhouse 3. Condominium You Choice? 1 Does the house have an indoor garage (1=Yes/0=No)? 1 Desired House Type: SingleFamily Has indoor garage? Yes Press any key to continue . . .
Here is another example of running the program:
Enter the type of house you want to purchase 1. Single Family 2. Townhouse 3. Condominium You Choice? 2 Does the house have an indoor garage (1=Yes/0=No)? 6 Desired House Type: Townhouse Has indoor garage? No Press any key to continue . . .
Notice that only two conditions are evaluated. Any condition other than these two is not considered. Because there can be other alternatives, the C# language provides an alternate else as the last resort. Its formula is:
if(Condition1) Statement1; else if(Condition2) Statement2; else Statement-n; |
if(Condition1) Statement1; else if(Condition2) Statement2; else if(Condition3) Statement3; else Statement-n; |
The compiler will check the first condition. If Condition1 is true, it executes Statement1. If Condition1 is false, then the compiler will check the second condition. If Condition2 is true, it will execute Statement2. When the compiler finds a Condition-n to be true, it will execute its corresponding statement. It that Condition-n is false, the compiler will check the subsequent condition. This means you can include as many conditions as you see fit using the else if statement. If after examining all the known possible conditions you still think that there might be an unexpected condition, you can use the optional single else. Here is an example:
using static System.Console;
public enum HouseType
{
Unknown,
SingleFamily,
Townhouse,
Condominium
}
public class Exercise
{
public static int Main()
{
var type = HouseType.Unknown;
var choice = 0;
var garage = "";
WriteLine("Enter the type of house you want to purchase");
WriteLine("1. Single Family");
WriteLine("2. Townhouse");
WriteLine("3. Condominium");
Write("You Choice? ");
choice = int.Parse(ReadLine());
if (choice == 1)
type = HouseType.SingleFamily;
else if (choice == 2)
type = HouseType.Townhouse;
else if (choice == 3)
type = HouseType.Condominium;
else
type = HouseType.Unknown;
Write("Does the house have an indoor garage (1=Yes/0=No)? ");
var answer = int.Parse(ReadLine());
if (answer == 1)
garage = "Yes";
else
garage = "No";
WriteLine("\nDesired House Type: {0}", type);
WriteLine("Has indoor garage? {0}", garage);
return 0;
}
}
Here is an example of running the program:
Enter the type of house you want to purchase 1. Single Family 2. Townhouse 3. Condominium You Choice? 3 Does the house have an indoor garage (1=Yes/0=No)? 0 Desired House Type: Condominium Has indoor garage? No Press any key to continue . . .
Options on Conditional Statements
Going To a Statement
In the flow of your code, you can jump from one statement or line to another. To make this possible, the C# language forvides an operator named goto. Before using it, first create or insert a name on a particular section of code or in a method. The name, also called a label, is made of one word and it can be anything. That name is followed by a colon ":". Here is an example:
public class VaccinationCampaign
{
public static void Main()
{
proposition:
}
}
In the same way, you can create as many labels as you want. The name of each label must be unique among the other labels in the same section of code (in the same scope). Here are examples:
public class VaccinationCampaign
{
public static void Main()
{
proposition:
something:
TimeToLeave:
}
}
After creating the label(s), you can create a condition so that, when that condition is true, code execution would jump to a designated label. To do this, in the body of the condition, type goto followed by the label. Here are examples:
using static System.Console; public class VaccinationCampaign { public static int Main() { int nbr = 148; if (nbr < 200) { goto higher; } else { goto lower; } higher: WriteLine("Result: " + 245.55); goto end; lower: WriteLine("Result: " + 105.75); goto end; end: WriteLine("=================================================="); return 0; } }
This would produce:
Result: 245.55 ================================================== Press any key to continue . . .
Here is another version of the program:
using static System.Console;
public class VaccinationCampaign
{
public static int Main()
{
int nbr = 348;
if (nbr < 200)
{
goto higher;
}
else
{
goto lower;
}
higher:
WriteLine("Result: " + 245.55);
goto end;
lower:
WriteLine("Result: " + 105.75);
goto end;
end:
WriteLine("==================================================");
return 0;
}
}
This would produce:
esult: 105.75 ================================================= ress any key to continue . . .
Negating a Statement
As you should be aware by now, Boolean algebra stands by two values, True and False, that are opposite each other. If you have a Boolean value or expression, to let you validate its opposite, the C-based languages provide the ! operator that is used to get the logical reverse of a Boolean value or of a Boolean expression. The formula to use it is:
!expression
To use this operator, type ! followed by a logical expression. The expression can be a simple Boolean value. To make the code easier to read, it is a good idea to put the negative expression in parentheses. Here is an example:
public class Exercise
{
public void Create()
{
bool employeeIsFullTime = true;
string opposite = (!employeeIsFullTime).ToString();
}
}
In this case, the ! (Not) operator is used to change the logical value of the variable. When a Boolean variable has been "notted", its logical value has changed. If the logical value was true, it would be changed to false and vice versa. Therefore, you can inverse the logical value of a Boolean variable by "notting" or not "notting" it.
Conditional Returns of Methods
When performing its assignment, a method can encounter different situations, a method can return only one value but you can make it produce a result that depends on some condition.
Returning From a Method
Normally, when defining a void method, it doesn't return a value. Here is an example:
public class Exercise
{
private void Show()
{
}
}
In reality, a void method can perform a return, as long as it does not return a true value. This is used to signal to the compiler that it is time to get out of the method. To add such as flag, in the appropriate section of the void method, simply type return;. Here is an example:
public class Exercise
{
private void Show()
{
Blah Blah Blah
return;
}
}
In this case, the return; statement doesn't serve any true purpose. It can be made useful when associated with a conditional statement.
Introduction to Recursion
Recursion if the ability for a method (or functtion) to call itself. A possible problem is that the method could keep calling itself and never stops. Therefore, the method must define how it would stop calling itself and get out of the body of the method.
A type of formula to create a recursive method is:
return-value method-name(parameter(s), if any) { Optional Action . . . method-name(); Optionan Action . . . }
A recursive method starts with a return value. If it would not return a value, you can define it with void. After its name, the method can use 0, one, or more parameters. Most of the time, a recursive method uses at least one parameter that it would modify. In the body of the method, you can take the necessary actions. There are no particular steps to follow when implementing a recursive method but there are two main rules to observe:
For an example of counting decrementing odd numbers, you could start by creating a method that uses a parameter of type integer. To exercise some control on the lowest possible values, we will consider only positive numbers. In the body of the method, we will display the current value of the argument, subtract 2, and recall the method itself. Here is our method:
using static System.Console;
public class Algebra
{
private static int result = 0;
public static void OddNumbers(int a)
{
if (a >= 1)
{
result += a;
a -= 2;
OddNumbers(a);
}
}
public static int Main()
{
const int number = 9;
OddNumbers(number);
WriteLine("Number: " + result);
WriteLine("==================================================");
return 0;
}
}
This would produce:
Number: 25 ================================================== Press any key to continue . . .
Notice that the method calls itself in its body.
Checking for Nullity
Comparing an Object to Nullity
Consider a class as folows:
public class House { public string Bedrooms; }
If a variable of a class was previously used but has been removed from memory, the variable has become null. Sometimes, you will be interested to find out whether an object is null. To perform this operation, you can compare the object to the null value. Here is an example:
using static System.Console;
public class House
{
public string Bedrooms;
}
public class Exercise
{
static int Main()
{
House habitat = null;
WriteLine("Real Estate");
WriteLine("House Description");
if (habitat == null)
WriteLine("There is no way to describe this house.");
WriteLine("==========================================");
return 0;
}
}
This would produce:
Real Estate House Description There is no way to describe this house. ========================================== Press any key to continue . . .
On the other hand, to find out whether an object is not null, you can use the != operator with the null keyword as the right operand. Here is an example:
using static System.Console;
public class House
{
public string Bedrooms;
}
public class Exercise
{
static int Main()
{
House habitat = new House();
habitat.Bedrooms = "5";
WriteLine("Real Estate");
WriteLine("House Description");
if (habitat != null)
WriteLine("Number of Bedrooms: {0}", habitat.Bedrooms);
WriteLine("==========================================");
return 0;
}
}
This would produce:
Real Estate House Description Number of Bedrooms: 5 ========================================== Press any key to continue . . .
Obviously the reason you are checking the nullity of an object is so you can take an appropriate action one way or another. Here is an example:
using static System.Console;
public class House
{
public string Bedrooms;
}
public class Exercise
{
static int Main()
{
House habitat = new House();
habitat.Bedrooms = "5";
WriteLine("Real Estate");
WriteLine("House Description");
if (habitat == null)
{
WriteLine("Apparently this house has not(yet) been built.");
}
else
{
WriteLine("Number of Bedrooms: {0}", habitat.Bedrooms);
}
WriteLine("==========================================");
return 0;
}
}
The Null Conditional Operator
Consider a class used to describe some houses:
public class House { public int Bedrooms; public House() { Bedrooms = 1; } }
We already saw how to find out whether an object of such a class is currently valid. Here is an example:
using static System.Console;
public class House
{
public int Bedrooms;
public House()
{
Bedrooms = 1;
}
}
public class Exercise
{
static int Main()
{
int beds = -1;
House habitat = new House();
if (habitat == null)
{
beds = 0;
}
else
{
beds = 3;
}
WriteLine("Real Estate");
WriteLine("House Description");
WriteLine("Number of Bedrooms: {0}", beds);
WriteLine("==========================================");
return 0;
}
}
In this case, we are trying to access a member of the class (getting the value of a property) only if the object is null. To simplify this operation, the C# language provides the null-conditional operator represented as ?. (the question mark immediately followed by a period). To apply it, use it to access the member of a class. Here is an example:
using static System.Console; public class House { public int Bedrooms; public House() { Bedrooms = 1; } } public class Exercise { static int Main() { int ? beds = 0; House habitat = new House(); beds = habitat?.Bedrooms; WriteLine("Real Estate"); WriteLine("House Description"); WriteLine("Number of Bedrooms: {0}", beds); WriteLine("=========================================="); return 0; } }
This would produce:
Real Estate ouse Description umber of Bedrooms: 1 ========================================= ress any key to continue . . .
The ?. operator checks whether the variable on its left is currently holding a null value. If it is, nothing happens. If it doesn't, then the member on its right is accessed and the operation that must be performed proceeds.
The Null-Coalescing Operator ??
Remember that, when declaring a variable of a primitive type, you can add a question mark to the data type to specify that the variable can have a nullable value. Here is an example:
using static System.Console;
public class Exercise
{
public static int Main()
{
double? distance = null;
WriteLine();
return 0;
}
}
At one time, you may want to assign the value of such a variable to another variable. If the variable is holding null, it means it does not have a value, so assigning to another variable would be meaningless. A solution is to first check whether the variable is currently holding null or an actual value. That is, you can ask the compiler to check whether the variable is currently null or it holds a value:
To support this, the C# language provides the null-coalescent operator: "??". The formula to use it is:
TargetVariable = OriginalVariable ?? AlternateValue;
You must have declared the OriginalVariable and it must be able to hold null, which is done by adding ? to it. You can first declare the TargetVariable or declare it when initializing it. Of course, both variables must be compatible. Here is an example of using the ?? operator:
using static System.Console;
public class Exercise
{
public static int Main()
{
double? distance = null;
double? fromTo = null;
WriteLine("Distance 1: {0}", distance);
WriteLine("Distance 2: {0}", fromTo);
fromTo = distance ?? 135.85;
WriteLine("Distance 1: {0}", distance);
WriteLine("Distance 2: {0}", fromTo);
WriteLine();
return 0;
}
}
The fromTo = distance ?? 135.85; means that:
The above code would produce:
Distance 1: Distance 2: Distance 1: Distance 2: 135.85 Press any key to continue . . .
Here is another version of the program:
using static System.Console; public class Exercise { public static int Main() { double? distance = null; double? fromTo = null; WriteLine("Distance 1: {0}", distance); WriteLine("Distance 2: {0}", fromTo); WriteLine("---------------------"); fromTo = distance ?? 135.85; WriteLine("Distance 1: {0}", distance); WriteLine("Distance 2: {0}", fromTo); WriteLine("---------------------"); distance = 8284.26; fromTo = distance ?? 135.85; WriteLine("Distance 1: {0}", distance); WriteLine("Distance 2: {0}", fromTo); return 0; } }
This time, the program would produce:
Distance 1: Distance 2: --------------------- Distance 1: Distance 2: 135.85 --------------------- Distance 1: 8284.26 Distance 2: 8284.26 Press any key to continue . . .
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2001-2018, FunctionX | Next |
|