﻿ Lesson 24: Introduction to Logical Operations

If Two Values Are Equal

Introduction to Comparisons

A comparison is a Boolean operation that finds out the relationship between two values. The operation produces a result of true or false. The comparison is performed between two values of the same type.

To let you perform comparisons and validations on values, you can use some symbols referred to as Boolean operators. The operator can be included between two operands as in:

`operand1 operator operand2`

This is referred to as a Boolean expression. Practical Learning: Introducing Logical Operations

1. Start Microsoft Visual Studio. In the Visual Studio 2019 dialog box, click Create a New Project and click Next (if Microsoft Visual Studio was already running, on the main menu, click File -> New -> Project...)
2. In the list of projects templates, click Windows Forms App (.NET Framework)
3. Click Next
4. Change the project Name to Chemistry05
5. Click Create
6. In the Solution Explorer, right-click Chemistry05 -> Add -> Class...
7. In the middle list, make sure Class is selected.
Change the file Name to Element
9. Right-click inside the Code Editor -> Remove and Sort Usings
10. Create the class as follows:
```namespace Chemistry05
{
public enum Phase
{
Gas,
Liquid,
Solid,
Unknown
}

public class Element
{
public string Symbol { get; set; }
public string ElementName { get; set; }
public int AtomicNumber { get; set; }
public double AtomicWeight { get; set; }
public Phase Phase { get; set; }

public Element()
{
}

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;
}
}
}```
11. Design the form as follows: Control (Name) Text GroupBox Element Detais Label Symbol: TextBox txtSymbol Label Element Name: TextBox txtElementName Label Atomic Number: TextBox txtAtomicNumber Label Atomic Weight: TextBox txtAtomicWeight Label Phase: TextBox txtPhase
12. Right-click the form and click View Code View
13. Right-click anywhere in the document and click Remove and Sort Usings
14. Change the constructor as follows:
```using System.Windows.Forms;

namespace Chemistry05
{
public partial class Chemistry : Form
{
public Chemistry()
{
InitializeComponent();

Element p = new Element(15, "P", "Phosphorus", 30.973761998) { Phase = Phase.Solid };

p.Phase = Phase.Solid;

txtSymbol.Text = p.Symbol;
txtElementName.Text = p.ElementName;
txtAtomicNumber.Text = p.AtomicNumber.ToString();
txtAtomicWeight.Text = p.AtomicWeight.ToString();
txtPhase.Text = p.Phase.ToString();
}
}
}``` The Equality Operator ==

To compare two variables for equality, C# provides the == operator. The formula to use it 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 can be illustrated as follows: It is important to make a distinction between the assignment "=" and the logical equality operator "==". The first 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.

Initializing a Boolean Variable

In our introductions to Boolean values, we saw that, to initialize or specify the value of a Boolean variable, you can assign a true or false value. A Boolean variable can also be initialized with a Boolean expression. Here is an example:

```public class Exercise
{
private void Create()
{
bool employeeIsFullTime = position == "Manager";
}
}```

To make your code easy to read, you should include the logical expression in parentheses. This can be done as follows:

```public class Exercise
{
string GetEmployeePosition()
{
return "Associate Director";
}

public void Create()
{
string position = "";

bool employeeIsFullTime = (position == "Manager");
}
}```

Introduction to Conditions

if an Operand is Equal to a Value

A conditional statement is a logical expression that produces a true or false result. You can then use that result as you want. To create a logical expression, you use a Boolean operator like the == operator we introduced above. To assist you with this, the C# language provides an operator named if. The formula to use it in a method of a class is:

`if(condition) statement;`

If you are using Microsoft Visual Studio, 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: The condition can be the type of Boolean operation we saw for the == operator. That is, the condition can have the following formula:

`operand1 Boolean-operator operand2`

Any of the operands can be a constant or the name of a variable. The operator can be == we saw earlier. The whole expression is the condition. If the expression produces a true result, then the statement would execute.

If you are working in a method of a class,. if the if statement is short, you can write it on the same line with the condition that is being checked. Here is an example:

If the statement is long, you can write it on a line different from that of the if condition.

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 Learning: Introducing Conditions

1. Change the design of the form as follows: Control (Name) Text Label Atomic Number: TextBox txtAtomicNumber Button btnFind Find GroupBox Element Detais Label Symbol: TextBox txtSymbol Label Element Name: TextBox txtElementName Label Atomic Weight: TextBox txtAtomicWeight Label Phase: TextBox txtPhase
2. Double-click the Find button

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 "}". This would be done as follows:

```public class AmploymentApplication
{
if(employmentStatus == 1)
{
. . .
. . .
. . .
}
}```

Iif you are working the body of a method, if you omit the brackets, only the statement that immediately follows the condition would be executed. The section between the curly brackets is the body of the conditional statement. Practical Learning: Creating an IF Condition

1. Change the document as follows:
```using System.Windows.Forms;

namespace Chemistry05
{
public partial class Chemistry : Form
{
public Chemistry()
{
InitializeComponent();
}

private void btnFind_Click(object sender, System.EventArgs e)
{
Element elm = new Element()
{
ElementName = "Sulfur",
AtomicWeight = 32.059,
Symbol = "S",
AtomicNumber = 16,
Phase = Phase.Solid
};

int number = int.Parse(txtAtomicNumber.Text);

if( number == elm.AtomicNumber)
{
txtSymbol.Text       = elm.Symbol;
txtElementName.Text  = elm.ElementName;
txtAtomicWeight.Text = elm.AtomicWeight.ToString();
txtPhase.Text        = elm.Phase.ToString();
}
}
}
}``` 3. In the Atomic Number text box, type 2 and click Find (nothing happens)
4. Click Find (nothing happens)
5. In the Atomic Number text box, type 16
6. Click Find: if a Condition is True/False

One way to formulate a conditional statement is to find out whether a situation is true or false. In this case, one of the operands must be a Boolean value as true or false. The other operand can be a Boolean variable. Here is an example:

```public class Exercise
{
public void Create()
{
bool employeeIsFullTime = false;;

if( false == employeeIsFullTime)
{

}
}
}```

One of the operands can also be an expression that holds a Boolean value.

Imagine that you want to evaluate the condition as true. Here is an example:

```public class Exercise
{
public void Create()
{
bool employeeIsFullTime = true;

if( employeeIsFullTime == true)
{

}
}
}```

If a Boolean variable (currently) holds a true value (at the time you are trying to access it), when you are evaluating the expression as being true, you can omit the == true or the true == expression in your statement. Therefore, the above expression can be written as follows:

```public class Exercise
{
public void Create()
{
bool employeeIsFullTime = true;

. . . No Change

if( employeeIsFullTime)
{

}
}
}```

This would produce the same result as previously.

Introduction to Multiple Conditions

Just as you can create one if condition, you can write more than one to consider different outcomes of an expression or an object. Practical Learning: Introducing Multiple Conditions

1. Change the code of the event as follows:
```using System.Windows.Forms;

namespace Chemistry05
{
public partial class Chemistry : Form
{
public Chemistry()
{
InitializeComponent();
}

private void btnFind_Click(object sender, System.EventArgs e)
{
Element selected = new Element();

Element h = new Element(1, "H", "Hydrogen", 1.008) { Phase = Phase.Gas };
Element he = new Element(2, "He", "Helium", 4.002602) { Phase = Phase.Gas };
Element li = new Element(3, "Li", "Lithium", 6.94) { Phase = Phase.Solid };
Element be = new Element(4, "Be", "Beryllium", 9.0121831) { Phase = Phase.Solid };
Element b = new Element(5, "B", "Boron", 10.81) { Phase = Phase.Solid };
Element c = new Element(name: "Carbon", mass: 12.011, symbol: "C", number: 6) { Phase = Phase.Solid };
Element n = new Element(7);
n.Symbol = "N";
n.AtomicWeight = 14.007;
n.ElementName = "Nitrogen";
n.Phase = Phase.Gas;

Element o = new Element("O")
{
AtomicNumber = 8,
ElementName = "Oxygen",
AtomicWeight = 15.999,
Phase = Phase.Gas
};
Element f = new Element("F")
{
AtomicNumber = 9,
ElementName = "Fluorine",
AtomicWeight = 15.999,
Phase = Phase.Gas
};
Element ne = new Element("Ne")
{
AtomicNumber = 10,
ElementName = "Neon",
AtomicWeight = 20.1797,
Phase = Phase.Gas
};
Element na = new Element(11, "Na", "Sodium", 22.98976928) { Phase = Phase.Solid };
Element mg = new Element(12, "Mg", "Magnesium", 24.305) { Phase = Phase.Solid };
Element al = new Element(13, "Al", "Aluminium", 26.9815385) { Phase = Phase.Solid };
Element si = new Element()
{
ElementName = "Silicon",
AtomicWeight = 28.085,
Symbol = "Si",
AtomicNumber = 14,
Phase = Phase.Solid
};
Element p  = new Element()
{
ElementName = "Phosphorus", AtomicWeight = 30.973761998,
Symbol = "P", AtomicNumber = 15, Phase = Phase.Solid
};
Element s  = new Element() { AtomicNumber = 16, ElementName = "Sulfur", Symbol = "S", AtomicWeight = 32.059, Phase = Phase.Solid };
Element cl = new Element() { Phase = Phase.Gas, AtomicWeight = 35.446, ElementName = "Chlorine", AtomicNumber = 17, Symbol = "Cl" };

int number = int.Parse(txtAtomicNumber.Text);

if (number == 1)
{
selected = h;
}
if (number == 2)
{
selected = he;
}
if (number == 3)
{
selected = li;
}
if (number ==  4) { selected = be; }
if (number ==  5) { selected = b;  }
if (number ==  6) { selected = c;  }
if (number ==  7) { selected = n;  }
if (number ==  8) { selected = o;  }
if (number ==  9) { selected = f;  }
if (number == 10) { selected = ne; }
if (number == 11) { selected = na; }
if (number == 12) { selected = mg; }
if (number == 13) { selected = al; }
if (number == 14) { selected = si; }
if (number == 15) { selected = p;  }
if (number == 16) { selected = s;  }
if (number == 17) { selected = cl; }

txtSymbol.Text       = selected.Symbol;
txtElementName.Text  = selected.ElementName;
txtAtomicWeight.Text = selected.AtomicWeight.ToString();
txtPhase.Text        = selected.Phase.ToString();
}
}
}``` 3. In the text box, type a number between 1 (included) and 17 (included)
4. Click the Find button: 5. Close the form and close your programming environment
6. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
7. In the list of projects templates, click Windows Forms App (.NET Framework)
8. Click Next
9. Change the project Name to ESCAPE1
10. Click Create
11. Design the form as follows: Control (Name) Text Other Properties Label Eastern Shore Company Associates for Production Entertainment GroupBox Bill Preparation Label Account Type: ComboBox cbxAccountsTypes Items: ```Hospital Commercial``` Label DVR Service: TextBox txtDVRService 0.00 TextAlign: Right Label Sports Package: TextBox txtSportsPackage 0.00 TextAlign: Right Label Sports Package: TextAlign: Right TextBox txtSportsPackage TextAlign: Right Button btnEvaluate Evaluate Bill GroupBox Bill Summary Label Package Fee: TextBox txtPackageFee 0.00 TextAlign: Right Label Local Taxes: TextBox txtLocalTaxes TextAlign: Right Label Sub-Total: TextBox txtSubTotal TextAlign: Right Label State Taxes: TextBox txtStateTaxes TextAlign: Right Label FCC Fee: TextBox txtFCCFee TextAlign: Right Label Amount Due: TextBox txtAmountDue TextAlign: Right
12. Double-click the Calculate button
13. Right-click inside the Code Editor and click Remove and Sort Usings

What Else?

Introduction to if...else Conditions

If you use an if condition to perform an operation and if the result is true, we saw that you could execute the statement. Any other result would be ignored. To let you address an alternative to an if condition, the C# language provides a keyword named else. The formula to use it is:

```if(condition)
statement1;
else
statement2;```

Once again, the condition can be a Boolean operation. If the condition is true, then the statement1 would execute. If the condition is false, then the compiler would execute the statement2 in the else section. Here is an example:

```using System;
using System.Windows.Forms;

namespace ConditionalStatements
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btnValidate_Click(object sender, EventArgs e)
{
if (txtMolecuole.Text == "H2O")
MessageBox.Show("That's write, the molecule of water is H2O.", "Chemistry");
else
MessageBox.Show("Not really! It's time you refresh your knowledge of chemistry",
"Chemistry");
}
}
}```

Here is an example of executing the program:  Practical Learning: Introducing if...else Conditions

1. Implement the event as follows:
```using System;
using System.Windows.Forms;

namespace ESCAPE1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btnEvaluate_Click(object sender, EventArgs e)
{
double packageFee;

if (cbxAccountsTypes.Text == "Residential")
packageFee = 14.25;
else // Hospital, Commercial, Governmentl
packageFee = 18.05;

double dvr = double.Parse(txtDVRService.Text);
double sport = double.Parse(txtSportsPackage.Text);
var subTotal = packageFee + dvr + sport;
var fcc = subTotal * 0.00250881;
var local = (subTotal + fcc) * 0.0372668;
var state = (subTotal + fcc) * 0.0082493;

txtPackageFee.Text = packageFee.ToString("F");
txtSubTotal.Text = subTotal.ToString("F");
txtFCCFee.Text = fcc.ToString("F");
txtLocalTaxes.Text = local.ToString("F");
txtStateTaxes.Text = state.ToString("F");
txtAmountDue.Text = (subTotal + fcc + local + state).ToString("F");
}
}
}``` 3. Click the Evaluate Bill button: 4. Change the following values:
```DVR Service: 8.95
Sports Package: 12.15```
5. Click the Evaluate Bill button: 6. Make the following changes:
```Account Type:   Residential
DVR Service:    0.00
Sports Package: 9.25```
7. Click the Evaluate Bill button: 9. Change the Form1.cs document as follows:
```using System;
using System.Windows.Forms;

namespace ESCAPE1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

double SpecifyFee()
{
double value;

if (cbxAccountsTypes.Text == "Residential")
value = 16.55;
else // Hospital, Commercial, Governmentl
value = 19.25;

return value;
}

void Summarize(double fee, double st, double fcc, double tax1, double tax2)
{
txtPackageFee.Text = fee.ToString("F");
txtSubTotal.Text = st.ToString("F");
txtFCCFee.Text = fcc.ToString("F");
txtLocalTaxes.Text = tax1.ToString("F");
txtStateTaxes.Text = tax2.ToString("F");
txtAmountDue.Text = (st + fcc + tax1 + tax2).ToString("F");

return;
}

private void btnEvaluate_Click(object sender, EventArgs e)
{
double packageFee = SpecifyFee();

double dvr = double.Parse(txtDVRService.Text);
double sport = double.Parse(txtSportsPackage.Text);

double subTotal = packageFee + dvr + sport;
double fcc = subTotal * 0.00250881;
double local = (subTotal + fcc) * 0.0372668;
double state = (subTotal + fcc) * 0.0082493;

Summarize(packageFee, subTotal, fcc, local, state);
return;
}
}
}```
10. To execute, press Ctrl + F5

The Bodies of a Composite Conditional Statement

We saw that if the statement of an if condition is long or if it involves many statements, you can create a body for its statement(s). In the same way, if an else condition produces a long of many statements, add a body deliminated by curcly brackets to it. This would be done as follows:

```if(condition)
statement1;
else
{
statement2;
}```

Either if the if or else can have a body whether the other has a body or not. You will decide based on your goal:

```if(condition){
if-statement1;
if-statement2;
. . .
if-statement_n;
}
else{
else-statement1;
else-statement2;
. . .
else-statement_n;
}```

Logical Difference

We already know that the == operator is used to find out if two values are the same. The opposite is to find out whether two values are different. The operator to do this is !=. It can be illustrated as follows A typical Boolean expression involves two operands separated by a logical operator. Both operands must be of the same type. These rules apply to the logical difference. It can be used on numbers, strings, and Boolean variables. If both operands are different, the operation produces a true result. If they are the exact same, the operation produces false. Practical Learning: Ending the Lesson