Fundamentals of Boolean Values

Introduction

A Boolean value is a value that can assume one of two values: True or False. Besides its value, the operations that can be performed on the value are those of comparisons. To perform such operations, you use some symbols called Boolean operators.

Practical LearningPractical Learning: Introducing Conditions

  1. Start Microsoft Visual Studio
  2. To create a new application, on the main menu, click File -> New -> Project...
  3. In the middle list, click Empty Project (.NET Framework)
  4. Change the Name to Chemistry02
  5. Press Enter
  6. To create a new file, in the Solution Explorer, right-click Chemistry02 -> Add -> Class...
  7. In the middle list, click make sure Class is selected.
    Change the Name of the file to Element
  8. Click Add
  9. Complete the Employee.cs file as follows:
    namespace Chemistry02
    {
        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;
            }
        }
    }
  10. To create a new file, in the Solution Explorer, right-click Chemistry02 -> Add -> Class...
  11. In the middle list, make sure Class is selected.
    Change the Name to Chemistry and press Enter
  12. Complete the file as follows:
    using static System.Console;
    
    namespace Chemistry02
    {
        public class Chemistry
        {
            public static int Main()
            {
                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);
    
                WriteLine("Chemistry - Nitrogen");
                WriteLine("------------------------");
                Write("Symbol: ");
                WriteLine(n.Symbol);
                Write("Element Name: ");
                WriteLine(n.ElementName);
                Write("Atomic Number: ");
                WriteLine(n.AtomicNumber);
                Write("Atomic Weight: ");
                WriteLine(n.AtomicWeight);
                WriteLine("========================");
    
                return 0;
            }
        }
    }
  13. To execute the application, on the main menu, click Debug -> Start Debugging
    hemistry - Nitrogen
    -----------------------
    ymbol: N
    lement Name: Nitrogen
    tomic Number: 7
    tomic Weight: 14.007
    =======================
    ress any key to continue . . .
  14. Press Enter to close the DOS window and return to your programming environment
  15. Change the Chemistry class as follows:
    using static System.Console;
    
    namespace Chemistry02
    {
        public class Chemistry
        {
            public static int Main()
            {
                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);
    
                WriteLine("Chemistry - Period Table");
                WriteLine("------------------------");
                Write("In the periodic table, what it the atomic number for hydrogen (1-8): ");
                int answer = int.Parse(ReadLine());
    
                Element elm = new Element(answer);
    
                Clear();
    
                WriteLine("Your answer: {0}", answer);
                WriteLine("========================");
    
                return 0;
            }
        }
    }
  16. To execute, on the main menu, click Debug -> Start Without Debugging
    Chemistry - Period Table
    ------------------------
    In the periodic table, what it the atomic number for hydrogen (1-8):
  17. When prompted, read the question and type 1
    Chemistry - Period Table
    ------------------------
    In the periodic table, what it the atomic number for hydrogen (1-8): 1
  18. Ppress Enter
    Your answer: 1
    ========================
    Press any key to continue . . .
  19. Press Enter to close the window and return to your programming environment

A Boolean Type

A variable is referred to as Boolean if it can hold a value as true or false. To support such values, the C# language provides a data type named bool. Use it to declare the variable. Here is an example:

public class Exercise
{
    static int Main()
    {
        bool drinkingUnderAge;

		return 0;
    }
}

Alternatively, you can declare a Boolean variable using the Boolean data type. The Boolean data type is part of the System namespace. Here is an example:

public class Exercise
{
    static int Main()
    {
        bool drinkingUnderAge;
    	Boolean theFloorIsCoveredWithCarpet;

		return 0
    }
}

A Boolean Value

A Boolean variable can hold only a true or a false value. Therefore, to initialize a Boolean variable, assign true or false to it. Here is an example:

public class Exercise
{
    static int Main()
    {
        bool drinkingUnderAge = true;

        return 0;
    }
}

At any time, you can also also set one of those values to the variable. Here is an example:

using static System.Console;

public class Exercise
{
    static int Main()
    {
        bool drinkingUnderAge;

		. . . 
    
        drinkingUnderAge = true;
        
        return 0;
    }
}

As is the case for all types, to declare a Boolean variable, you can use the var keyword. In this case, you must immediately initialize the variable. Here is an example:

public class Exercise
{
    static int Main()
    {
        var drinkingUnderAge = true;

        return 0;
    }
}

To display the value of a Boolean variable on the console, you can type its name in the parentheses of the Write() or the WriteLine() methods of the Console class. Here is an example:

using static System.Console;

public class Exercise
{
    static int Main()
    {
        var drinkingUnderAge = true;

        WriteLine("Drinking Under Age: {0}", drinkingUnderAge);
        return 0;
    }
}

This would produce:

Drinking Under Age: True
Press any key to continue . . .

Once again, at any time and when you judge it necessary, you can change the value of the Boolean variable by assigning it a true or false value. Here is an example:

using static System.Console;

public class Exercise
{
    static int Main()
    {
        var drinkingUnderAge = true;

        WriteLine("Drinking Under Age: {0}", drinkingUnderAge);

        drinkingUnderAge = false;
        WriteLine("Drinking Under Age: {0}", drinkingUnderAge);
        return 0;
    }
}

This would produce:

Drinking Under Age: True
Drinking Under Age: False
Press any key to continue . . .

Getting the Value of a Boolean Variable

As reviewed for the other data types, you can request the value of a Boolean variable from the user. In this case, the user must type either True (or true) or False (or false) and you can retrieve it using the Read() or the ReadLine() methods of the Console class. Here is an example:

using static System.Console;

public class Exercise
{
    static int Main()
    {
        var drivingUnderAge = false;

        WriteLine("Were you driving under age?");
        Write("If Yes, enter True. Otherwise enter False: ");
        drivingUnderAge = bool.Parse(Console.ReadLine());

        WriteLine("\nWas Driving Under Age: {0}\n", drivingUnderAge);
        return 0;
    }
}

Here is an example of running the program:

Were you driving under age?
If Yes, enter True. Otherwise enter False: true

Was Driving Under Age: True

Press any key to continue . . .

Introduction to Logical Operators

Overview

A logical operation is one that performs a comparison to find out whether a value, a variable, or an expression is true or false. To support such operations, C# provides many operators.

The Equality Operator ==

To compare two variables for equality, you can use the == operator. The formula to follow is:

value1 == Value2

The equality operation is used to find out whether two variables (or one variable and a constant) hold the same value. The operation proceed as follows:

The result of a comparison can be assigned to a Boolean variable. Here is an example:

using static System.Console;

public class Exercise
{
    static int Main()
    {
        var value1 = 15;
        var value2 = 24;
        bool result = value1 == value2;

        Write("Value 1 = ");
        WriteLine(value1);
        Write("Value 2 = ");
        WriteLine(value2);
        WriteLine("The comparison for {0} == {1} produces {2}", value1, value2, result);
        WriteLine("==========================================");

        return 0;
    }
}

This would produce:

Value 1 = 15
Value 2 = 24
The comparison for 15 == 24 produces False
==========================================
Press any key to continue . . .

It is important to make a distinction between the assignment "=" and the logical equality operator "==". The first one is used to give a new value to a variable, as in Number = 244. The operand on the left side of = must always be a variable and never a constant. The == operator is never used to assign a value; this would cause an error. The == operator is used only to compare two values. The operands on both sides of == can be variables, constants, or one can be a variable while the other is a constant. If you use one operator in place of the other, you would receive an error when you compile the program.

Initializing a Boolean Variable

To initialize or specify the value of a Boolean variable, you can assign a true or false value.

if a Condition is True

Introduction

A conditional statement is a comparison-based expression that produces a true or false result. Consider the following program:

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

        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 static System.Console;

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

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

        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;

        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 static System.Console;

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

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

        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;

        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.

Practical LearningPractical Learning: Introducing Boolean Conditions

  1. Change the Chemistry class as follows:
    using static System.Console;
    
    namespace Chemistry02
    {
        public class Chemistry
        {
            public static int Main()
            {
                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);
    
                WriteLine("Chemistry - Period Table");
                WriteLine("------------------------");
                Write("In the periodic table, what it the atomic number for hydrogen (1-9): ");
                int answer = int.Parse(ReadLine());
    
                Element elm = new Element(answer);
    
                Clear();
    
                WriteLine("Your answer: {0}", answer);
    
                if(elm.AtomicNumber == h.AtomicNumber)
                    WriteLine("Good Answer");
                WriteLine("========================");
    
                return 0;
            }
        }
    }
  2. To execute, on the main menu, click Debug -> Start Without Debugging
    Chemistry - Period Table
    ------------------------
    In the periodic table, what it the atomic number for hydrogen (1-9):
  3. When prompted, read the question, type 1 and press Enter
    Your answer: 1
    Good Answer
    ========================
    Press any key to continue . . .
  4. Press Enter to close the window and return to your programming environment

The Body of a Conditional Statement

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 static System.Console;

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

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

        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;
            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. As an alternative to create an if conditional statement, right-click the section where you want to add the code and click Code Snippet... Double-click Visual C#. In the list, double-click if:

Using Many Conditional Statements

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

using static System.Console;

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

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

        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;
        if (choice == 2)
            type = HouseType.Townhouse;
        if (choice == 3)
            type = HouseType.Condominium;

        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 Many Conditional Statements

  1. Change the Chemistry class as follows:
    using static System.Console;
    
    namespace Chemistry02
    {
        public class Chemistry
        {
            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("Ne")
                {
                    AtomicNumber = 10,
                    ElementName = "Neon",
                    AtomicWeight = 20.1797,
                };
    
                WriteLine("Chemistry - Period Table");
                WriteLine("------------------------");
                Write("Enter an atomic number to explorer (1-10): ");
                int answer = int.Parse(ReadLine());
    
                if(answer ==  1) elm = h;
                if(answer ==  2) elm = he;
                if(answer ==  3) elm = li;
                if(answer ==  4) elm = be;
                if(answer ==  5) elm = b;
                if(answer ==  6) elm = c;
                if(answer ==  7) elm = n;
                if(answer ==  8) elm = o;
                if(answer ==  9) elm = f;
                if(answer == 10) elm = ne;
    
                Clear();
    
                WriteLine("Chemistry - " + elm.ElementName);
                WriteLine("------------------------");
                WriteLine("Symbol:        " + elm.Symbol);
                WriteLine("Element Name:  " + elm.ElementName);
                WriteLine("Atomic Number: " + elm.AtomicNumber);
                WriteLine("Atomic Weight: " + elm.AtomicWeight);
                WriteLine("========================");
    
                return 0;
            }
        }
    }
  2. To execute, on the main menu, click Debug -> Steart Debugging
    Chemistry - Period Table
    ------------------------
    Enter an atomic number to explorer (1-10):
  3. When requested, type 8 and press Enter
    Chemistry - Oxygen
    ------------------------
    Symbol:        O
    Element Name:  Oxygen
    Atomic Number: 8
    Atomic Weight: 15.999
    ========================
    Press any key to continue . . .
  4. Press Enter to close the window and return to your programming environment

Introduction to Boolean Values and Classes

A Boolean Field

Like the other types of variables we used in previous lessons, a Boolean variable can be made a field of a class. You declare it like any other variable, using the bool keyword or the Boolean data type. Here is an example:

public class House
{
    string typeOfHome;
    int beds;
    double baths;
    int stories;
    bool hasCarGarage;
    int yearBuilt;
    double value;
}

When initializing an object that has a Boolean variable as a member, simply assign true or false to the variable. In the same way, you can retrieve or check the value that a Boolean member variable is holding by simply accessing it. Here are examples:

using static System.Console;

public class House
{
    public string typeOfHome;
    public int beds;
    public double baths;
    public int stories;
    public bool hasCarGarage;
    public int yearBuilt;
    public double value;
}

public class Program
{
    static int Main()
    {
        var Condominium = new
        {
            hasCarGarage = false,
            yearBuilt = 2019,
            baths = 1.5,
            stories = 18,
            value = 155825,
            beds = 2,
            typeOfHome = "C"
        };

        WriteLine("=//= Altair Realtors =//=");
        WriteLine("=== Property Listing ===");
        WriteLine("Type of Home:        {0}", Condominium.typeOfHome);
        WriteLine("Number of Bedrooms:  {0}", Condominium.beds);
        WriteLine("Number of Bathrooms: {0}", Condominium.baths);
        WriteLine("Number of Stories:   {0}", Condominium.stories);
        WriteLine("Year Built:          {0}", Condominium.yearBuilt);
        WriteLine("Has Car Garage:      {0}", Condominium.hasCarGarage);
        WriteLine("Monetary Value:      {0}\n", Condominium.value);

        return 0;
    }
}

This would produce:

=//= Altair Realtors =//=
=== Property Listing ===
Type of Home:        C
Number of Bedrooms:  2
Number of Bathrooms: 1.5
Number of Stories:   18
Year Built:          2019
Has Car Garage:      False
Monetary Value:      155825

Press any key to continue . . .

A Boolean Arguments

Like parameters of the other types, you can pass an argument of type bool or Boolean to a method. In the body of the method, treat the argument as holding a true or false value. When calling the method, make sure you provide such a value. Here is an example:

using static System.Console;

public class Patient
{
    public string Name;
    public int Gender;

    public void Diagnose(bool pregnant)
    {
        if(pregnant == true)
        {
            WriteLine("The following vaccinations are recommended:");
            WriteLine("1. Influenza (Inactivated)");
            WriteLine("2. Tdap");
            WriteLine("3. Hepatitis B: The patient should consult her physician");
        }
    }
}

public class VaccinationCampaign
{
    public static int Main()
    {
        bool answer = false;
        Patient person = new Patient();

        WriteLine("Department of Health");
        WriteLine("--------------------------------------------------");
        WriteLine("Patient's Diagnosis");
        Write("Patient's Name: ");
        person.Name = ReadLine();
        Write("Patient's Gender (0 - Unknown, 1 - Male, 2 - Female): ");
        person.Gender = int.Parse(ReadLine());
        Write("Is the patient pregnant (True/False): ");
        answer = bool.Parse(ReadLine());

        Clear();

        WriteLine("Department of Health");
        WriteLine("--------------------------------------------------");
        WriteLine("Patient's Diagnosis");
        WriteLine("Name:   " + person.Name);
        WriteLine("Gender: " + person.Gender);
        person.Diagnose(answer);
        WriteLine("==================================================");

        return 0;
    }
}

Here is an example of running the program:

Department of Health
--------------------------------------------------
Patient's Diagnosis
Patient's Name: Rodrigo Marquez
Patient's Gender (0 - Unknown, 1 - Male, 2 - Female): 1
Is the patient pregnant (True/False): False

Here is the result when pressing Enter:

Department of Health
--------------------------------------------------
Patient's Diagnosis
Name:   Rodrigo Marquez
Gender: 1
==================================================
Press any key to continue . . .

Here is another example or testing the program:

Department of Health
--------------------------------------------------
Patient's Diagnosis
Patient's Name: Clarice Fonglong
Patient's Gender (0 - Unknown, 1 - Male, 2 - Female): 2
Is the patient pregnant (True/False): True

Here is the result:

Department of Health
--------------------------------------------------
Patient's Diagnosis
Name:   Clarice Fonglong
Gender: 2
The following vaccinations are recommended:
1. Influenza (Inactivated)
2. Tdap
3. Hepatitis B: The patient should consult her physician
==================================================
Press any key to continue . . .

Conditional Operators

A Different Value: !=

Two values are different when they are not the same and two variables of the same type are not equal if they are not holding the same value. To perform such a comparison, you can use the != operator. The formula to follow is:

value1 != value

Its logic is as follows:

Less Than Or Equal

Practical LearningPractical Learning: Testing for Inequality

  1. Change the Chemistry class as follows:
    using static System.Console;
    
    namespace Chemistry02
    {
        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);
    
                WriteLine("Chemistry - Period Table");
                WriteLine("------------------------------------------------");
                Write("In the periodic table, what it the atomic number for fluorine (1-11): ");
                int answer = int.Parse(ReadLine());
    
                elm = new Element(answer);
    
                Clear();
    
                WriteLine("Your answer: {0}", answer);
                WriteLine("------------------------------------------------");
    
                if (answer == 9)
                {
                    WriteLine("Good Answer");
                    Describe(f);
                }
                   
                if (answer != 9)
                    WriteLine("Wrong Answer: Please review your periodic table");
    
                WriteLine("================================================");
    
                return 0;
            }
        }
    }
  2. To execute, on the main menu, click Debug -> Steart Debugging
    Chemistry - Period Table
    ------------------------------------------------
    In the periodic table, what it the atomic number for fluorine (1-11):
  3. When requested, type 9 and press Enter
    Your answer: 9
    ------------------------------------------------
    Good Answer
    Chemistry - Fluorine
    ------------------------
    Symbol:        F
    Element Name:  Fluorine
    Atomic Number: 9
    Atomic Weight: 15.999
    ================================================
    Press any key to continue . . .
  4. Press Enter to close the window and return to your programming environment

Greater Than or Equal To: >

To find out if one value is greater than the other, you can use the > operator. Its formula is:

Value1 > Value2

Both operands, in this case Value1 and Value2, can be variables or the left operand can be a variable while the right operand is a constant. If the value on the left of the > operator is greater than the value on the right side or a constant, the comparison produces a true or positive value . Otherwise, the comparison renders false or null:

Greater Than

 

The Greater Than or Equal Operator >=

The greater than or the equality operators can be combined to produce an operator as follows: >=. This is the "greater than or equal to" operator. Its syntax is:

Value1 >= Value2

A comparison is performed on both operands: Value1 and Value2. If the value of Value1 and that of Value2 are the same, the comparison produces a true or positive value. If the value of the left operand is greater than that of the right operand,, the comparison produces true or positive also. If the value of the left operand is strictly less than the value of the right operand, the comparison produces a false or null result:

Flowchart: Greater Than Or Equal To

Practical LearningPractical Learning: Finding Out Whether a Value is Greater or Equal

  1. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  2. In the middle list, click Empty Project (.NET Framework) and set the project Name to GasUtilityCompany1
  3. Click OK
  4. On the main menu, click View -> Class View
  5. In the Class View, right-click GasUtilityCompany1 -> Add -> Class...
  6. In the middle list, make sure Class is selected.
    Change the name to Calculations and click Add
  7. Type code as follows:
    static public class Calculations
    {
        public static double Multiply(double a, double b)
        {
            return a * b;
        }
    }
  8. In the Class View, right-click GasUtilityCompany1 -> Add -> Class...
  9. Type GasUtilityCompany as the name of the class
  10. Click Add
  11. Complete the document as follows:
    using static System.Console;
    using static System.Environment;
    
    namespace GasUtilityCompany1
    {
        public class GasUtilityCompany
        {
            private static void Calculate(double consumption)
            {
                double pricePerCCF = 0.00;
    
                if (consumption >= 0.50)
                {
                    pricePerCCF = 35.00;
                }
    
                double monthlyCharges = Calculations.Multiply(consumption, pricePerCCF);
    
                WriteLine("Gas Utility Company");
                WriteLine("------------------------");
                WriteLine("Consumption:     {0}", consumption);
                WriteLine("Price per CCF:   {0:C}", pricePerCCF);
                WriteLine("Monthly Charges: {0:C}", monthlyCharges);
                WriteLine("=========================");
    }
            public static void Main()
            {
                WriteLine("Gas Utility Company");
                WriteLine("-----------------------------------");
                Write("How much gas did the customer consume? ");
                double consumption = double.Parse(ReadLine());
    
                Clear();
    
                Calculate(consumption);
            }
        }
    }
  12. To execute the application, on the menu, click Debug -> Start Without Debugging:
    Gas Utility Company
    -----------------------------------
    How much gas did the customer consume?
  13. When prompted, type a decimal number between 1 and 10, such as 1.26:
    Gas Utility Company
    -----------------------------------
    How much gas did the customer consume? 1.26
  14. Press Enter
    Gas Utility Company
    ------------------------
    Consumption:     1.26
    Price per CCF:   $35.00
    Monthly Charges: $44.10
    =========================
    Press any key to continue . . .
  15. Press Enter to close the window and return to your programming environment

A Value Lower Than: <

To find out whether one value is lower than another, use the < operator. Its syntax is:

Value1 < Value2

Flowchart: Less Than

Less Than of Equal To: <=

The previous two operations can be combined to compare two values. This allows you to know if two values are the same or if the first is less than the second. The operator used is <= and its syntax is:

Value1 <= Value2

The <= operation performs a comparison as any of the last two. If both Value1 and Value2 hold the same value, result is true or positive. If the left operand, in this case Value1, holds a value lower than the second operand, in this case Value2, the result is still true.

Less Than Or Equal

Here is a summary table of the logical operators we have studied:

Operator Meaning Example Opposite
== Equality to a == b !=
!= Not equal to 12 != 7 ==
< Less than 25 < 84 >=
<= Less than or equal to Cab <= Tab >
> Greater than 248 > 55 <=
>= Greater than or equal to Val1 >= Val2 <

The Logical Not Operator !

When a variable is declared and receives a value (this could be done through initialization or a change of value) in a program, it becomes alive. It can then participate in any necessary operation. The compiler keeps track of every variable that exists in the program being processed. When a variable is not being used or is not available for processing (in visual programming, it would be considered as disabled) to make a variable (temporarily) unusable, you can nullify its value. C# considers that a variable whose value is null is stern. To render a variable unavailable during the evolution of a program, apply the logical not operator which is !. Its syntax is:

!Value

There are two main ways you can use the logical not operator. As we will learn when studying conditional statements, the most classic way of using the logical not operator is to check the state of a variable. To nullify a variable, you can write the exclamation point to its left.

When a variable holds a value, it is "alive". To make it not available, you can "not" it. When a variable has been "notted", its logical value has changed. If the logical value was true, which is 1, it would be changed to false, which is 0. Therefore, you can inverse the logical value of a variable by "notting" or not "notting" it.

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2018, FunctionX Next