Introduction to Logical Operations
Introduction to Logical Operations
Introduction to Conditions
Foundations of Comparisons
We are already familiar with numbers and strings. A value is said to be Boolean if can be evaluated as being true or being false.
A comparison consists of establishing a relationship between two values, such as to find out whether both values are equal or one of them is greated than the other, etc. To perform a comparison, you use two operands and an operator as in the following formula:
operand1 operator operand2
This is the basic formula of a Boolean expression.
Practical Learning: Introducing Conditions
using static System.Console;
WriteLine("FUN DEPARTMENT STORE");
WriteLine("=======================================================");
WriteLine("Item Preparation");
WriteLine("-------------------------------------------------------");
WriteLine("Enter the following pieces of information");
WriteLine("-------------------------------------------------------");
int discountRate = 75;
double discountAmount = 0.00;
double discountedPrice = 0.00;
Write("Item Name: ");
string itemName = ReadLine();
Write("Original Price: ");
double originalPrice = double.Parse(ReadLine());
Write("Days in Store: ");
int daysInStore = int.Parse(ReadLine());
discountAmount = originalPrice * discountRate / 100;
discountedPrice = originalPrice - discountAmount;
WriteLine("+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+");
WriteLine("FUN DEPARTMENT STORE");
WriteLine("=======================================================");
WriteLine("Store Inventory");
WriteLine("-------------------------------------------------------");
WriteLine($"Item Name: {itemName}");
WriteLine($"Original Price: {originalPrice}");
WriteLine($"Days in Store: {daysInStore}");
WriteLine($"Discount Rate: {discountRate}%");
WriteLine($"Discount Amount: {discountAmount:f}");
WriteLine($"Discounted Price: {discountedPrice:f}");
WriteLine("=======================================================");
FUN DEPARTMENT STORE ======================================================= Item Preparation ------------------------------------------------------- Enter the following pieces of information ------------------------------------------------------- Item Name: Tulip Sleeved Sheath Dress Original Price: 89.95 Days in Store: 28 +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ FUN DEPARTMENT STORE ======================================================= Store Inventory ------------------------------------------------------- Item Name: Tulip Sleeved Sheath Dress Original Price: 89.95 Days in Store: 28 Discount Rate: 75% Discount Amount: 67.46 Discounted Price: 22.49 ======================================================= Press any key to close this window . . .
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. To assist you with this, the C# language provides an operator named if. The primary formula to use it is:
if(condition) statement;
If you are using Microsoft Visual Studio, to use a code snippet 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 have the following formula:
operand1 Boolean-operator operand2
Any of the operands can be a constant or the name of a variable. The operator is a logical one. The whole expression is the condition. If the expression produces a true result, then the statement would execute.
If the if statement is short, you can write it on the same line with the condition that is being checked. This would be done as follows:
if( operand1 Boolean-operator operand2) statement;
If the statement is long, you can write it on a line different from that of the if condition. This would be done as follows:
if( operand1 Boolean-operator operand2) statement;
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.
The Body of a Conditional Statement
The statement, whether written on the same line as the if condition or on the next line, is called the body of the 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:
if( operand1 operator operand2) { . . . . . . . . . }
In this case, the section from { (included) to } (included) is also referred to as the body of the conditional statement. If you omit the brackets, only the statement or line of code that immediately follows the condition would be executed.
Fundamentals of Boolean Values
Introduction
A value is said to be Boolean if it is true or it is false. In fact, the two available Boolean values are true and false.
To let you declare a Boolean variable, the C# language provides a data type named bool. Here is an example of declaring a Boolean variable:
bool drinkingUnderAge;
To initialize a Boolean variable or to change its value, assign true or false to it. Here is an example:
bool drinkingUnderAge = true;
In this case, you can also declare the variable as var, object or dynamic. Make sure you initialize the variable when declaring it. Remember that, in any case, after declaring a (Boolean) variable, you can later change its value by assigning an updated value to it. Here is an example:
var drinkingUnderAge = true;
// Blah blah blah
drinkingUnderAge = false;
A Constant Boolean Variable
If you are planning to use a Boolean variable whose value will never change, you can declare it as a constant. To do this, apply the const keyword to the variable and initialize it. Here is an example:
const bool driverIsSober = true;
As reviewed for the other data types, you can request the value of a Boolean variable from your users. The user must type "true" or "false", case-insensitive. This means that the user can type "true", "True", "TRUE", "False", "FALSE", or "false", etc. When the user has typed the value, you must convert that value to a Boolean. As seen with the other data types, to convert a value, you can write Parse() and, in the parentheses, put the value to be converted. Here is an example:
using static System.Console; bool drinkingUnderAge = true; Write("Are you drunk (Type 'true' or 'false'): "); string answer = ReadLine(); drinkingUnderAge = bool.Parse(answer);
Presenting a Boolean Value
To display the value of a Boolean variable to the console, pass the name of the variable to a Write() or a WriteLine() method. Here are examples:
using static System.Console; bool drinkingUnderAge = true; Write("The driver was operating under age: "); WriteLine(drinkingUnderAge); WriteLine("-----------------------------------------"); drinkingUnderAge = false; Write("The person was driving under age: "); WriteLine(drinkingUnderAge); WriteLine("=========================================");
In the same way, if you had requested a Boolean value from a user, you can display it. Here is an example:
using static System.Console; bool drinkingUnderAge = true; Write("Are you drunk (Type 'true' or 'false'): "); string answer = ReadLine(); drinkingUnderAge = bool.Parse(answer); WriteLine("============================================"); WriteLine("Your answer was: {0}", drinkingUnderAge); WriteLine("============================================");
Here is an example of running the program:
Are you drunk (Type 'true' or 'false'): TRUE ============================================ Your answer was: True ============================================ Press any key to close this window . . .
Assigning a Logical Expression to a Boolean Variable
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. This would be done as follows:
bool variable = operand1 Boolean-operator operand2;
To make your code easy to read, you should include the logical expression in parentheses. This can be done as follows:
bool variable = (operand1 Boolean-operator operand2);
Fundamentals of Logical Operators
Introduction
As introduced in the previous lesson, a logical comparison is used to establish the logical relationship between two values, a variable and a value, or two variables. There are various operators available to perform such comparisons.
A Value Less Than Another: <
To find out whether one value is lower than another, the operator to use is <. Its formula is:
Value1 < Value2
This operation can be illustrated as follows:
To indicate that you are performing a comparison for a "Less Than" operation, in the parentheses of the conditional statement, you can start with a keyword named is. We saw that the formula of a conditional statement is:
if(condition) statement(s);
This time, the formula of the condition becomes:
operand1 is Boolean-operator operand2
For a "Less Than" operation, the formula of the conditional statement is:
if(operand1 is < operand2) statement(s);
Here is an example:
using static System.Console;
const double salary = 36_000;
string employmentStatus = "Full-Time";
if( salary is < 40000 )
employmentStatus = "Part-Time";
WriteLine("Employee Record");
WriteLine("-----------------------------");
WriteLine("Yearly Salary: {0}", salary);
WriteLine("Employment Status: {0}", employmentStatus);
WriteLine("=============================");
This would produce:
Employee Record ----------------------------- Yearly Salary: 36000 Employment Status: Full-Time ============================= Press any key to close this window . . .
Practical Learning: Comparing for a Lesser Value
using static System.Console; WriteLine("FUN DEPARTMENT STORE"); WriteLine("======================================================="); WriteLine("Item Preparation"); WriteLine("-------------------------------------------------------"); WriteLine("Enter the following pieces of information"); WriteLine("-------------------------------------------------------"); int discountRate = 75; double discountAmount = 0.00; double discountedPrice = 0.00; Write("Item Name: "); string itemName = ReadLine(); Write("Original Price: "); double originalPrice = double.Parse(ReadLine()); Write("Days in Store: "); int daysInStore = int.Parse(ReadLine()); if(daysInStore is < 60) discountRate = 50; if(daysInStore is < 45) discountRate = 35; if(daysInStore is < 35) discountRate = 15; if(daysInStore is < 15) discountRate = 0; discountAmount = originalPrice * discountRate / 100; discountedPrice = originalPrice - discountAmount; WriteLine("+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+"); WriteLine("FUN DEPARTMENT STORE"); WriteLine("======================================================="); WriteLine("Store Inventory"); WriteLine("-------------------------------------------------------"); WriteLine($"Item Name: {itemName}"); WriteLine($"Original Price: {originalPrice}"); WriteLine($"Days in Store: {daysInStore}"); WriteLine($"Discount Rate: {discountRate}%"); WriteLine($"Discount Amount: {discountAmount:f}"); WriteLine($"Discounted Price: {discountedPrice:f}"); WriteLine("=======================================================");
FUN DEPARTMENT STORE ======================================================= Item Preparation ------------------------------------------------------- Enter the following pieces of information ------------------------------------------------------- Item Name: Tulip Sleeved Sheath Dress Original Price: 89.95 Days in Store: 28 +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ FUN DEPARTMENT STORE ======================================================= Store Inventory ------------------------------------------------------- Item Name: Tulip Sleeved Sheath Dress Original Price: 89.95 Days in Store: 28 Discount Rate: 15% Discount Amount: 13.49 Discounted Price: 76.46 ======================================================= Press any key to close this window . . .
FUN DEPARTMENT STORE ======================================================= Item Preparation ------------------------------------------------------- Enter the following pieces of information ------------------------------------------------------- Item Name: Tulip Sleeved Sheath Dress Original Price: 89.95 Days in Store: 46 +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ FUN DEPARTMENT STORE ======================================================= Store Inventory ------------------------------------------------------- Item Name: Tulip Sleeved Sheath Dress Original Price: 89.95 Days in Store: 46 Discount Rate: 50% Discount Amount: 44.98 Discounted Price: 44.98 ======================================================= Press any key to close this window . . .
using static System.Console; WriteLine("FUN DEPARTMENT STORE"); WriteLine("======================================================="); WriteLine("Payroll Preparation"); WriteLine("-------------------------------------------------------"); WriteLine("Enter the following pieces of information"); WriteLine("-------------------------------------------------------"); WriteLine("Employee Information"); WriteLine("-------------------------------------------------------"); Write("First Name: "); string firstName = ReadLine(); Write("Last Name: "); string lastName = ReadLine(); Write("Hourly Salary: "); double hSalary = double.Parse(ReadLine()); WriteLine("-------------------------------------------------------"); WriteLine("Time worked"); WriteLine("-------------------------------------------------------"); Write("Monday: "); double mon = double.Parse(ReadLine()); Write("Tuesday: "); double tue = double.Parse(ReadLine()); Write("Wednesday: "); double wed = double.Parse(ReadLine()); Write("Thursday: "); double thu = double.Parse(ReadLine()); Write("Friday: "); double fri = double.Parse(ReadLine()); double time_worked = mon + tue + wed + thu + fri; double net_pay = hSalary * time_worked; WriteLine("+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+"); WriteLine("FUN DEPARTMENT STORE"); WriteLine("======================================================="); WriteLine("Payroll Evaluation"); WriteLine("======================================================="); WriteLine("Employee Information"); WriteLine("-------------------------------------------------------"); WriteLine($"Full Name: {firstName} {lastName}"); WriteLine($"Hourly Salary: {hSalary:f}"); WriteLine("======================================================="); WriteLine("Time Worked Summary"); WriteLine("--------+---------+-----------+----------+-------------"); WriteLine(" Monday | Tuesday | Wednesday | Thursday | Friday"); WriteLine("--------+---------+-----------+----------+-------------"); WriteLine($" {mon:f} | {tue:f} | {wed:f} | {thu:f} | {fri:f}"); WriteLine("========+=========+===========+==========+============="); WriteLine(" Pay Summary"); WriteLine("-------------------------------------------------------"); WriteLine($" Total Time: {time_worked:f}"); WriteLine("-------------------------------------------------------"); WriteLine($" Net Pay: {net_pay:f}"); WriteLine("=======================================================");
First Name: | Michael |
Last Name: | Carlock |
Hourly Salary: | 28.25 |
Monday | 7 |
Tuesday: | 8 |
Wednesday: | 6.5 |
Thursday: | 8.5 |
Friday: | 6.5 |
FUN DEPARTMENT STORE ======================================================= Payroll Preparation ------------------------------------------------------- Enter the following pieces of information ------------------------------------------------------- Employee Information ------------------------------------------------------- First Name: Michael Last Name: Carlock Hourly Salary: 28.25 ------------------------------------------------------- Time worked ------------------------------------------------------- Monday: 7 Tuesday: 8 Wednesday: 6.5 Thursday: 8.5 Friday: 6.5 +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ FUN DEPARTMENT STORE ======================================================= Payroll Evaluation ======================================================= Employee Information ------------------------------------------------------- Full Name: Michael Carlock Hourly Salary: 28.25 ======================================================= Time Worked Summary --------+---------+-----------+----------+------------- Monday | Tuesday | Wednesday | Thursday | Friday --------+---------+-----------+----------+------------- 7.00 | 8.00 | 6.50 | 8.50 | 6.50 ========+=========+===========+==========+============= Pay Summary ------------------------------------------------------- Total Time: 36.50 ------------------------------------------------------- Net Pay: 1031.12 ======================================================= Press any key to close this window . . .
First Name: | Catherine |
Last Name: | Busbey |
Hourly Salary: | 24.37 |
Monday | 9.50 |
Tuesday: | 8 |
Wednesday: | 10.50 |
Thursday: | 9 |
Friday: | 10.50 |
FUN DEPARTMENT STORE ======================================================= Payroll Preparation ------------------------------------------------------- Enter the following pieces of information ------------------------------------------------------- Employee Information ------------------------------------------------------- First Name: Catherine Last Name: Busbey Hourly Salary: 24.37 ------------------------------------------------------- Time worked ------------------------------------------------------- Monday: 9.5 Tuesday: 8 Wednesday: 10.5 Thursday: 9 Friday: 10.5 +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ FUN DEPARTMENT STORE ======================================================= Payroll Evaluation ======================================================= Employee Information ------------------------------------------------------- Full Name: Catherine Busbey Hourly Salary: 24.37 ======================================================= Time Worked Summary --------+---------+-----------+----------+------------- Monday | Tuesday | Wednesday | Thursday | Friday --------+---------+-----------+----------+------------- 9.50 | 8.00 | 10.50 | 9.00 | 10.50 ========+=========+===========+==========+============= Pay Summary ------------------------------------------------------- Total Time: 47.50 ------------------------------------------------------- Net Pay: 1157.58 ======================================================= Press any key to close this window . . .
A Value Greater Than Another: >
To find out if one value is greater than the other, the operator to use is >. Its formula is:
value1 is > 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. Otherwise, the comparison renders False. This operation can be illustrated as follows:
Here is an example:
using static System.Console;
const double salary = 42_000;
string employmentStatus = "Part-Time";
if( salary is > 40000 )
employmentStatus = "Full-Time";
WriteLine("Employee Record");
WriteLine("-----------------------------");
WriteLine("Yearly Salary: {0}", salary);
WriteLine("Employment Status: {0}", employmentStatus);
WriteLine("=============================");
This would produce:
Employee Record ----------------------------- Yearly Salary: 42000 Employment Status: Full-Time ============================= Press any key to close this window . . .
Practical Learning: Finding Out Whether a Value is Greater Than Another
using static System.Console; WriteLine("FUN DEPARTMENT STORE"); WriteLine("======================================================="); WriteLine("Payroll Preparation"); WriteLine("-------------------------------------------------------"); WriteLine("Enter the following pieces of information"); WriteLine("-------------------------------------------------------"); WriteLine("Employee Information"); WriteLine("-------------------------------------------------------"); Write("First Name: "); string firstName = ReadLine(); Write("Last Name: "); string lastName = ReadLine(); Write("Hourly Salary: "); double hSalary = double.Parse(ReadLine()); WriteLine("-------------------------------------------------------"); WriteLine("Time worked"); WriteLine("-------------------------------------------------------"); Write("Monday: "); double mon = double.Parse(ReadLine()); Write("Tuesday: "); double tue = double.Parse(ReadLine()); Write("Wednesday: "); double wed = double.Parse(ReadLine()); Write("Thursday: "); double thu = double.Parse(ReadLine()); Write("Friday: "); double fri = double.Parse(ReadLine()); double timeWorked = mon + tue + wed + thu + fri; double regTime = timeWorked; double overtime = 0.00; double overPay = 0.00; double regPay = hSalary * timeWorked; if(timeWorked is > 40.00) { regTime = 40.00; regPay = hSalary * 40.00; overtime = timeWorked - 40.00; overPay = hSalary * 1.50 * overtime; } double netPay = regPay + overPay; WriteLine("+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+"); WriteLine("FUN DEPARTMENT STORE"); WriteLine("======================================================="); WriteLine("Payroll Evaluation"); WriteLine("======================================================="); WriteLine("Employee Information"); WriteLine("-------------------------------------------------------"); WriteLine($"Full Name: {firstName} {lastName}"); WriteLine($"Hourly Salary: {hSalary:f}"); WriteLine("======================================================="); WriteLine("Time Worked Summary"); WriteLine("--------+---------+-----------+----------+-------------"); WriteLine(" Monday | Tuesday | Wednesday | Thursday | Friday"); WriteLine("--------+---------+-----------+----------+-------------"); WriteLine($" {mon:f} | {tue:f} | {wed:f} | {thu:f} | {fri:f}"); WriteLine("========+=========+===========+==========+============="); WriteLine(" Pay Summary"); WriteLine("-------------------------------------------------------"); WriteLine(" Time Pay"); WriteLine("-------------------------------------------------------"); WriteLine($" Regular: {regTime:f} {regPay:f}"); WriteLine("-------------------------------------------------------"); WriteLine($" Overtime: {overtime:f} {overPay:f}"); WriteLine("======================================================="); WriteLine($" Net Pay: {netPay:f}"); WriteLine("=======================================================");
FUN DEPARTMENT STORE ======================================================= Payroll Preparation ------------------------------------------------------- Enter the following pieces of information ------------------------------------------------------- Employee Information ------------------------------------------------------- First Name: Michael Last Name: Carlock Hourly Salary: 28.25 ------------------------------------------------------- Time worked ------------------------------------------------------- Monday: 7 Tuesday: 8 Wednesday: 6.5 Thursday: 8.5 Friday: 6.5 +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ FUN DEPARTMENT STORE ======================================================= Payroll Evaluation ======================================================= Employee Information ------------------------------------------------------- Full Name: Michael Carlock Hourly Salary: 28.25 ======================================================= Time Worked Summary --------+---------+-----------+----------+------------- Monday | Tuesday | Wednesday | Thursday | Friday --------+---------+-----------+----------+------------- 7.00 | 8.00 | 6.50 | 8.50 | 6.50 ========+=========+===========+==========+============= Pay Summary ------------------------------------------------------- Time Pay ------------------------------------------------------- Regular: 36.50 1031.12 ------------------------------------------------------- Overtime: 0.00 0.00 ======================================================= Net Pay: 1031.12 ======================================================= Press any key to close this window . . .
FUN DEPARTMENT STORE ======================================================= Payroll Preparation ------------------------------------------------------- Enter the following pieces of information ------------------------------------------------------- Employee Information ------------------------------------------------------- First Name: Catherine Last Name: Busbey Hourly Salary: 24.37 ------------------------------------------------------- Time worked ------------------------------------------------------- Monday: 9.5 Tuesday: 8 Wednesday: 10.5 Thursday: 9 Friday: 10.5 +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ FUN DEPARTMENT STORE ======================================================= Payroll Evaluation ======================================================= Employee Information ------------------------------------------------------- Full Name: Catherine Busbey Hourly Salary: 24.37 ======================================================= Time Worked Summary --------+---------+-----------+----------+------------- Monday | Tuesday | Wednesday | Thursday | Friday --------+---------+-----------+----------+------------- 9.50 | 8.00 | 10.50 | 9.00 | 10.50 ========+=========+===========+==========+============= Pay Summary ------------------------------------------------------- Time Pay ------------------------------------------------------- Regular: 40.00 974.80 ------------------------------------------------------- Overtime: 7.50 274.16 ======================================================= Net Pay: 1248.96 ======================================================= Press any key to close this window . . .
|
|||
Previous | Copyright © 2001-2024, FunctionX | Monday 06 December 2021 | Next |
|