Home

Conditional Statements

 

if a Condition is True

 

Introduction

A conditional statement is an expression that produces a true or false result. You can use that result as you see fit. To create the expression, you use the Boolean operators we studied in the previous lesson. In the previous lesson, we saw only how to perform the operations and how to get the results, not how to use them. To use the result of a Boolean operation, the C# programming language provides some specific conditional operators.

 

Practical LearningPractical Learning: Introducing Conditional Expressions

  1. Start Microsoft Visual C# and create a Console Application named ElectronicStore2
  2. To create a new class, on the main menu, click Project -> Add Class...
  3. Set the Name of the class to StoreItem and click Add
  4. Complete the StoreItem.cs file as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ElectronicStore2
    {
        public enum ItemsCategories
        {
            Unknown,
            CablesAndConnectors,
            CellPhonesAndAccessories,
            Headphones,
            DigitalCameras,
            PDAsAndAccessories,
            TelephonesAndAccessories,
            TVsAndVideos,
            SurgeProtectors,
            Instructional
        }
    
        public class StoreItem
        {
            public long ItemNumber;
            public ItemsCategories Category;
            public string Make;
            public string Model;
            public string Name;
            public double UnitPrice;
    
            // An item whose characteristics are not (yet) defined
            public StoreItem()
            {
                ItemNumber = 0;
                Category = ItemsCategories.Unknown;
                Make = "Unknown";
                Model = "Unspecified";
                Name = "N/A";
                UnitPrice = 0.00D;
            }
            // An item that is known by its make, model, and unit price
            public StoreItem(long itmNbr, String make,
                       String model, double price)
            {
                ItemNumber = itmNbr;
                Category = ItemsCategories.Unknown;
                Make = make;
                Model = model;
                Name = "N/A";
                UnitPrice = price;
            }
            // An item that is known by its name and unit price
            public StoreItem(long itmNbr, String name, double price)
            {
                ItemNumber = itmNbr;
                Category = ItemsCategories.Unknown;
                Make = "Unknown";
                Model = "Unspecified";
                Name = name;
                UnitPrice = price;
            }
            // An item completely defined
            public StoreItem(long itmNbr, ItemsCategories category,
                          String make, String model, double price)
            {
                ItemNumber = itmNbr;
                Category = category;
                Make = make;
                Model = model;
                UnitPrice = price;
            }
        }
    }
  5. Save the file

if

Consider the following program:

using System;

public enum HouseType
{
    Unknown,
    SingleFamily,
    TownHouse,
    Condominium
}
Condominiums
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());

        Console.WriteLine("\nDesired House Type: {0}", type);
	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

Desired House Type: Unknown
Press any key to continue . . .

To check if an expression is true and use its Boolean result, you can use the if operator. Its formula is:

if(Condition) Statement;

The Condition can be the type of Boolean operation we studied in the previous lesson. That is, it can have the following formula:

Operand1 BooleanOperator Operand2

If the Condition produces a true result, then the compiler executes the Statement. If the statement to execute is short, you can write it on the same line with the condition that is being checked. Here is an example:

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;

        Console.WriteLine("\nDesired House Type: {0}", type);
	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
Press any key to continue . . .

If the Statement is too long, you can write it on a different line than the if condition. Here is an example:

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;

        Console.WriteLine("\nDesired House Type: {0}", type);
	return 0;
    }
}

You can also write the Statement on its own line even if the statement is short enough to fit on the same line with the Condition.

Although the (simple) if statement is used to check one condition, it can lead to executing multiple dependent statements. If that is the case, enclose the group of statements between an opening curly bracket “{“ and a closing curly bracket “}”. Here is an example:

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;
            Console.WriteLine("\nDesired House Type: {0}", type);
        }
	return 0;
    }
}

If you omit the brackets, only the statement that immediately follows the condition would be executed.

Just as you can write one if condition, you can write more than one. Here are examples:

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);
	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

Desired House Type: Condominium
Press any key to continue . . .

Practical LearningPractical Learning: Using the Simple if Condition

  1. Access the Program.cs file and change it as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ElectronicStore2
    {
        public class Program
        {
            private static StoreItem CreateStoreItem()
            {
                StoreItem sItem = new StoreItem();
                int Category;
    
                Console.WriteLine(
    		"To create a store item, enter its information");
                Console.Write("Item Number: ");
                sItem.ItemNumber = long.Parse(Console.ReadLine());
                Console.WriteLine("Category");
                Console.WriteLine("1.  Unknown/Miscellaneous");
                Console.WriteLine("2.  Cables and Connectors");
                Console.WriteLine("3.  Cell Phones and Accessories");
                Console.WriteLine("4.  Headphones");
                Console.WriteLine("5.  Digital Cameras");
                Console.WriteLine("6.  PDAs and Accessories");
                Console.WriteLine("7.  Telephones and Accessories");
                Console.WriteLine("8.  TVs and Videos - Plasma / LCD");
                Console.WriteLine("9.  Surge Protector");
                Console.WriteLine(
    		"10. Instructional and Tutorials (VHS & DVD)TVs and Videos");
                Console.Write("Your Choice? ");
                category = int.Parse(Console.ReadLine());
    
                if (Category == 1)
                    sItem.Category = ItemsCategories.Unknown;
                if (Category == 2)
                    sItem.Category = ItemsCategories.CablesAndConnectors;
                if (Category == 3)
                    sItem.Category = ItemsCategories.CellPhonesAndAccessories;
                if (Category == 4)
                    sItem.Category = ItemsCategories.Headphones;
                if (Category == 5)
                    sItem.Category = ItemsCategories.DigitalCameras;
                if (Category == 6)
                    sItem.Category = ItemsCategories.PDAsAndAccessories;
                if (Category == 7)
                    sItem.Category = ItemsCategories.TelephonesAndAccessories;
                if (Category == 8)
                    sItem.Category = ItemsCategories.TVsAndVideos;
                if (Category == 9)
                    sItem.Category = ItemsCategories.SurgeProtectors;
                if (Category == 10)
                    sItem.Category = ItemsCategories.Instructional;
    
                Console.Write("Make:        ");
                sItem.Make = Console.ReadLine();
                Console.Write("Model:       ");
                sItem.Model = Console.ReadLine();
                Console.Write("Unit Price:  ");
                sItem.UnitPrice = decimal.Parse(Console.ReadLine());
    
                return sItem;
            }
    
            static void DescribeStoreItem(StoreItem item)
            {
                Console.WriteLine("Store Item Description");
                Console.WriteLine("Item Number:   {0}", item.ItemNumber);
                Console.WriteLine("Category:      {0}", item.Category);
                Console.WriteLine("Make:          {0}", item.Make);
                Console.WriteLine("Model:         {0}", item.Model);
                Console.WriteLine("Unit Price:    {0:C}", item.UnitPrice);
            }
    
            static void Main()
            {
                string strTitle1 = "=-= Nearson Electonics =-=";
                string strTitle2 = "******* Store Items ******";
    
                StoreItem saleItem = CreateStoreItem();
    
                Console.WriteLine("");
                DescribeStoreItem(saleItem);
            }
        }
    }
  2. Execute the application to see the result. Here is an example:
     
    To create a store item, enter its information
    Item Number: 868264
    Category
    1.  Unknown/Miscellaneous
    2.  Cables and Connectors
    3.  Cell Phones and Accessories
    4.  Headphones
    5.  Digital Cameras
    6.  PDAs and Accessories
    7.  Telephones and Accessories
    8.  TVs and Videos - Plasma / LCD
    9.  Surge Protector
    10. Instructional and Tutorials (VHS & DVD)TVs and Videos
    Your Choice? 1
    Make:        Altec Lansing
    Model:       VS4221 Computer Speakers
    Unit Price:  85.95
    
    Store Item Description
    Item Number:   868264
    Category:      Unknown
    Make:          Altec Lansing
    Model:         VS4221 Computer Speakers
    Unit Price:    $85.95
    Press any key to continue . . .
    Speakers
  3. Close the DOS window

if…else

Here is an example of what we learned in the previous section:

using System;

public enum HouseType
{
    Unknown,
    SingleFamily,
    Townhouse,
    Condominium
}
Single Family
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 LearningPractical Learning: Using the if...else Condition

  1. Access the Program.cs file and, to use the if...else condition, change the file as follows:
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ElectronicStore2
    {
        class Program
        {
            static StoreItem CreateStoreItem()
            {
                StoreItem sItem = new StoreItem();
                int Category;
                double ItemPrice = 0D;
    
                Console.WriteLine(
    		"To create a store item, enter its information");
                Console.Write("Item Number: ");
                sItem.ItemNumber = long.Parse(Console.ReadLine());
                Console.WriteLine("Category");
                Console.WriteLine("1.  Unknown/Miscellaneous");
                Console.WriteLine("2.  Cables and Connectors");
                Console.WriteLine("3.  Cell Phones and Accessories");
                Console.WriteLine("4.  Headphones");
                Console.WriteLine("5.  Digital Cameras");
                Console.WriteLine("6.  PDAs and Accessories");
                Console.WriteLine("7.  Telephones and Accessories");
                Console.WriteLine("8.  TVs and Videos - Plasma / LCD");
                Console.WriteLine("9.  Surge Protector");
                Console.WriteLine(
    		"10. Instructional and Tutorials (VHS & DVD)TVs and Videos");
                Console.Write("Your Choice? ");
                Category = int.Parse(Console.ReadLine());
    
                if (Category == 1)
                    sItem.Category = ItemsCategories.Unknown;
                if (Category == 2)
                    sItem.Category = ItemsCategories.CablesAndConnectors;
                if (Category == 3)
                    sItem.Category = ItemsCategories.CellPhonesAndAccessories;
                if (Category == 4)
                    sItem.Category = ItemsCategories.Headphones;
                if (Category == 5)
                    sItem.Category = ItemsCategories.DigitalCameras;
                if (Category == 6)
                    sItem.Category = ItemsCategories.PDAsAndAccessories;
                if (Category == 7)
                    sItem.Category = ItemsCategories.TelephonesAndAccessories;
                if (Category == 8)
                    sItem.Category = ItemsCategories.TVsAndVideos;
                if (Category == 9)
                    sItem.Category = ItemsCategories.SurgeProtectors;
                if (Category == 10)
                    sItem.Category = ItemsCategories.Instructional;
    
                Console.Write("Make:        ");
                sItem.Make = Console.ReadLine();
                Console.Write("Model:       ");
                sItem.Model = Console.ReadLine();
                Console.Write("Unit Price:  ");
                ItemPrice = double.Parse(Console.ReadLine());
                if( ItemPrice <= 0 )
                    sItem.UnitPrice = 0.00D;
                else
                    sItem.UnitPrice = ItemPrice;
    
                return sItem;
            }
    
            static string GetItemCategory(ItemsCategories cat)
            {
                string strCategory = "Unknown";
    
                if (cat == ItemsCategories.CablesAndConnectors)
                    strCategory = "Cables & Connectors";
                if (cat == ItemsCategories.CellPhonesAndAccessories)
                    strCategory = "Cell Phones & Accessories";
                if (cat == ItemsCategories.Headphones)
                    strCategory = "Headphones";
                if (cat == ItemsCategories.DigitalCameras)
                    strCategory = "Digital Cameras";
                if (cat == ItemsCategories.PDAsAndAccessories)
                    strCategory = "PDAs & Accessories";
                if (cat == ItemsCategories.TelephonesAndAccessories)
                    strCategory = "Telephones & Accessories";
                if (cat == ItemsCategories.TVsAndVideos)
                    strCategory = "TVs & Videos";
                if (cat == ItemsCategories.SurgeProtectors)
                    strCategory = "Surge Protectors";
                if (cat == ItemsCategories.Instructional)
                    strCategory = "Instructional";
    
                return strCategory;
            }
    
            static void DescribeStoreItem(StoreItem item)
            {
                string strCategory = GetItemCategory(item.Category);
    
                Console.WriteLine("Store Item Description");
                Console.WriteLine("Item Number:   {0}", item.ItemNumber);
                Console.WriteLine("Category:      {0}", strCategory);
                Console.WriteLine("Make           {0}", item.Make);
                Console.WriteLine("Model:         {0}", item.Model);
                Console.WriteLine("Unit Price:    {0:C}", item.UnitPrice);
            }
    
            static void Main()
            {
                string strTitle1 = "=-= Nearson Electronics =-=";
                string strTitle2 = "******* Store Items ******";
    
                Console.WriteLine(strTitle1);
                Console.WriteLine(strTitle2);
                StoreItem saleItem = CreateStoreItem();
                Console.WriteLine("");
    
                Console.WriteLine(strTitle1);
                Console.WriteLine(strTitle2);
                DescribeStoreItem(saleItem);
                Console.WriteLine("");
            }
        }
    }
  2. Execute the application to test it. Here is an example:
     
    =-= Nearson Electronics =-=
    ******* Store Items ******
    To create a store item, enter its information
    Item Number: 937494
    Category
    1.  Unknown/Miscellaneous
    2.  Cables and Connectors
    3.  Cell Phones and Accessories
    4.  Headphones
    5.  Digital Cameras
    6.  PDAs and Accessories
    7.  Telephones and Accessories
    8.  TVs and Videos - Plasma / LCD
    9.  Surge Protector
    10. Instructional and Tutorials (VHS & DVD)TVs and Videos
    Your Choice? 5
    Make:        Canon
    Model:       EOS 30D
    Unit Price:  1395.95
    
    =-= Nearson Electronics =-=
    ******* Store Items ******
    Store Item Description
    Item Number:   937494
    Category:      Digital Cameras
    Make           Canon
    Model:         EOS 30D
    Unit Price:    $1,395.95
    
    Press any key to continue . . .
    Camera
  3. Close the DOS window

Logical Conjunction: AND

 

Introduction

Imagine that a real estate agent who will be using your program is meeting with a potential buyer and asking questions from the following program:

using System;

public enum HouseType
{
    Unknown,
    SingleFamily,
    Townhouse,
    Condominium
}

public class Program
{
    static int Main()
    {
        var type = HouseType.Unknown;
        var choice = 0;
        var value = 0D;

        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.Write("Up to how much can you afford? $");
        value = double.Parse(Console.ReadLine());

        Console.WriteLine("\nDesired House Type:      {0}", type);
        Console.WriteLine("Maximum value afforded:  {0:C}\n", value);

	return 0;
    }
}

Suppose a customer responds to these questions: she indicates that she wants single family house but she cannot afford more than $550,000:

Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 1
Up to how much can you afford? $550000

Desired House Type:      SingleFamily
Maximum value afforded:  $550,000.00

Press any key to continue . . .

When considering a house for this customer, there are two details to be validated here: the house must be a single family home, second, it must cost less than $550,001. We can create two statements as follows:

  1. The house is single family
  2. The house costs less than $550,000

From our list of real estate properties, if we find a house that is a single family home, we put it in our list of considered properties:

Type of House House
The house is single family True

On the other hand, if we find a house that is less than or equal to $550,000, we retain it:

Price Range Value
$550,000 True

One of the ways you can combine two comparisons is by joining them. For our customer, we want a house to meet BOTH criteria. If the house is a town house, based on the request of our customer, its conditional value is false. If the house is more than $550,000, the value of the Boolean Value is true. The Boolean operator used to join two criteria is called AND. This can be illustrated as follows:

Type of House House Value Result
Town House $625,000 Town House AND $625,000
False False False

In C#, the Boolean AND operator is performed using the && operator. Here is an example:

using System;

public enum HouseType
{
    Unknown,
    SingleFamily,
    Townhouse,
    Condominium
}

public class Exercise
{
    static int Main()
    {
        var type = HouseType.Unknown;
        var choice = 0;
        var value = 0D;

        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());

        Console.Write("Up to how much can you afford? $");
        value = double.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);
        Console.WriteLine("Maximum value afforded:  {0:C}", value);

        if (type == HouseType.SingleFamily && value <= 550000)
            Console.WriteLine("\nDesired House Matched");
	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
Up to how much can you afford? $450000

Desired House Type:      SingleFamily
Maximum value afforded:  $450,000.00

Desired House Matched
Press any key to continue . . .

By definition, a logical conjunction combines two conditions. To make the program easier to read, each side of the conditions can be included in parentheses. Here is an example:

using System;

public enum HouseType
{
    Unknown,
    SingleFamily,
    Townhouse,
    Condominium
}

public class Exercise
{
    static int Main()
    {
        var type = HouseType.Unknown;
        var choice = 0;
        var value = 0D;

        . . .

        if( (type == HouseType.SingleFamily) && (value <= 550000) )
            Console.WriteLine("\nDesired House Matched");
	return 0;
    }
}

Suppose we find a single family home. The first condition is true for our customer. With the AND Boolean operator, if the first condition is true, then we consider the second criterion. Suppose that the house we are considering costs $750,500: the price is out of the customer's range. Therefore, the second condition is false. In the AND Boolean algebra, if the second condition is false, even if the first is true, the whole condition is false. This would produce the following table:

Type of House House Value Result
Single Family $750,500 Single Family AND $750,500
True False False

This can be illustrated by the following run of the program:

using System;

public enum HouseType
{
    Unknown,
    SingleFamily,
    Townhouse,
    Condominium
}

class Program
{
    static void Main()
    {
        var type = HouseType.Unknown;
        int choice;
        var value = 0M;

        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.Write("Up to how much can you afford? $");
        value = decimal.Parse(Console.ReadLine());

        Console.WriteLine("\nDesired House Type:      {0}", type);
        Console.WriteLine("Maximum value afforded:  {0:C}", value);

        if (type == HouseType.SingleFamily && value <= 550000)
            Console.WriteLine("\nDesired House Matched");
        else
            Console.WriteLine("\nThe House Doesn't Match the Desired Criteria");
    }
}

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
Up to how much can you afford? $750000

Desired House Type:      SingleFamily
Maximum value afforded:  $750,000.00

The House Doesn't Match the Desired Criteria
Press any key to continue . . .

Suppose we find a townhouse that costs $420,000. Although the second condition is true, the first is false. In Boolean algebra, an AND operation is false if either condition is false:

Type of House House Value Result
Town House $420,000 Town House AND $420,000
False True False

Here is an example of running the above program:

Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 2
Up to how much can you afford? $420000

Desired House Type:      Townhouse
Maximum value afforded:  $420,000.00

The House Doesn't Match the Desired Criteria
Press any key to continue . . .

If we find a single family home that costs $345,000, both conditions are true. In Boolean algebra, an AND operation is true if BOTH conditions are true. This can be illustrated as follows:

Type of House House Value Result
Single Family $345,000 Single Family AND $345,000
True True True

This can be revealed in the following run of the above program:

Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 1
Up to how much can you afford? $345000

Desired House Type:      SingleFamily
Maximum value afforded:  $345,000.00

Desired House Matched
Press any key to continue . . .

These four tables can be resumed as follows:

If Condition1 is If Condition2 is Condition1
AND
Condition2
False False False
False True False
True False False
True True True

As you can see, a logical conjunction is true only of BOTH conditions are true.

Combining Conjunctions

As seen above, the logical conjunction operator is used to combine two conditions. In some cases, you will need to combine more than two conditions. Imagine a customer wants to purchase a single family house that costs up to $450,000 with an indoor garage. This means that the house must fulfill these three requirements:

  1. The house is a single family home
  2. The house costs less than $450,001
  3. The house has an indoor garage

Here the program that could be used to check these conditions:

using System;

public enum HouseType
{
    Unknown,
    SingleFamily,
    Townhouse,
    Condominium
}

public class Exercise
{
    static int Main()
    {
        var type = HouseType.Unknown;
        var choice = 0;
        var value = 0D;
        var hasIndoorGarage = false;

        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.Write("Up to how much can you afford? $");
        value = double.Parse(Console.ReadLine());

        Console.Write("Does the house have an indoor garage (1=Yes/0=No)? ");
        int ans = int.Parse(Console.ReadLine());

        Console.WriteLine("\nDesired House Type:      {0}", type);
        Console.WriteLine("Maximum value afforded:  {0:C}", value);
        Console.Write("House has indoor garage: ");
        if (ans == 1)
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");

        if ((type == HouseType.SingleFamily) && (value <= 550000) && (ans == 1))
            Console.WriteLine("\nDesired House Matched");
        else
            Console.WriteLine("\nThe House Doesn't Match the Desired Criteria");

        return 0;
    }
}

We saw that when two conditions are combined, the compiler first checks the first condition, followed by the second. In the same way, if three conditions need to be considered, the compiler evaluates the truthfulness of the first condition:

Type of House
A
Town House
False

If the first condition (or any condition) is false, the whole condition is false, regardless of the outcome of the other(s). If the first condition is true, then the second condition is evaluated for its truthfulness:

Type of House Property Value
A B
Single Family $655,000
True False

If the second condition is false, the whole combination is considered false:

A B A && B
True False False

When evaluating three conditions, if either the first or the second is false, since the whole condition would become false, there is no reason to evaluate the third. If both the first and the second conditions are false, there is also no reason to evaluate the third condition. Only if the first two conditions are true will the third condition be evaluated whether it is true:

Type of House Property Value Indoor Garage
A B C
Single Family $425,650 None
True True False

The combination of these conditions in a logical conjunction can be written as A && B && C. If the third condition is false, the whole combination is considered false:

A B A && B C A && B && C
True True True False False

To verify this, 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
Up to how much can you afford? $425000
Does the house have an indoor garage (1=Yes/0=No)? 0

Desired House Type:      SingleFamily
Maximum value afforded:  $425,000.00
House has indoor garage: No

The House Doesn't Match the Desired Criteria
Press any key to continue . . .

From our discussion so far, the truth table of the combinations can be illustrated as follows:

A B C A && B && C
False Don't Care Don't Care False
True False Don't Care False
True True False False

The whole combination is true only if all three conditions are true. This can be illustrated as follows:

A B C A && B && C
False False False False
False False True False
True False False False
True False True False
False True False False
False True True False
True True False False
True True True True
 

Logical Disjunction: OR

 

Introduction

Our real estate company has single family homes, townhouses, and condominiums. All of the condos have only one level, also referred to as a story. Some of the single family homes have one story, some have two and some others have three levels. All townhouses have three levels.

Another customer wants to buy a home. The customer says that he primarily wants a condo, but if our real estate company doesn't have a condominium, that is, if the company has only houses, whatever it is, whether a house or a condo, it must have only one level (story) (due to an illness, the customer would not climb the stairs). When considering the properties of our company, we would proceed with these statements:

  1. The property is a condominium
  2. The property has one story

If we find a condo, since all of our condos have only one level, the criterion set by the customer is true. Even if we were considering another (type of) property, it wouldn't matter. This can be resumed in the following table:

Type of House House
Condominium True

The other properties would not be considered, especially if they have more than one story:

Number of Stories Value
3 False

To check for either of two conditions, in Boolean algebra, you can use an operator called OR. We can show this operation as follows:

Condominium One Story Condominium OR 1 Story
True False True

In Boolean algebra, this type of comparison is performed using the OR operator. In C#, the OR operator is performed using the || operator. Here is an example:

using System;

public enum HouseType
{
    Unknown,
    SingleFamily,
    Townhouse,
    Condominium
}

public class Exercise
{
    static int Main()
    {
        var type = HouseType.Unknown;
        var choice = 0;
        var stories = 1;

        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.Write("How many stories? ");
        stories = int.Parse(Console.ReadLine());

        Console.WriteLine("\nDesired House Type: {0}", type);
        Console.WriteLine("Number of Stories:  {0}", stories);

        if ((type == HouseType.Condominium) || (stories == 1))
            Console.WriteLine("\nDesired House Matched");
        else
            Console.WriteLine("\nThe House Doesn't Match the Desired Criteria");

        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
How many stories? 6

Desired House Type: Condominium
Number of Stories:  6

Desired House Matched
Press any key to continue . . .

Suppose that, among the properties our real estate company has available, there is no condominium. In this case, we would then consider the other properties:

Type of House House
Single Family False

If we have a few single family homes, we would look for one that has only one story. Once we find one, our second criterion becomes true:

Type of House One Story Condominium OR 1 Story
False True True

This can be illustrated in the following run of the above program:

Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 1
How many stories? 1

Desired House Type: SingleFamily
Number of Stories:  1

Desired House Matched
Press any key to continue . . .

If we find a condo and it is one story, both criteria are true. This can be illustrated in the following table:

Type of House One Story Condominium OR 1 Story
False True True
True True True

The following run of the program demonstrates this:

Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 3
How many stories? 1

Desired House Type: Condominium
Number of Stories:  1

Desired House Matched
Press any key to continue . . .

A Boolean OR operation produces a false result only if BOTH conditions ARE FALSE:

If Condition1 is If Condition2 is Condition1 OR Condition2
False True True
True False True
True True True
False False False

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
How many stories? 2

Desired House Type: Townhouse
Number of Stories:  2

The House Doesn't Match the Desired Criteria
Press any key to continue . . .

Combinations of Disjunctions

As opposed to evaluating only two conditions, you may face a situation that presents three of them and must consider a combination of more than two conditions.

 

 

Previous Copyright © 2008-2016, FunctionX, Inc. Next