Boolean Conjunctions and Disjunctions
AIn the body of the conditional statement, you can create another conditional statement. This is referred to as nesting the condition. Here is an example:
html Lesson 13: Boolean Conjunctions and Disjunctions
Boolean Conjunctions and Disjunctions#
Conditional Conjunctions#
Nesting a Conditional Statement#
AIn the body of the conditional statement, you can create another conditional statement. This is referred to as nesting the condition. Here is an example:
<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void btnCalculate_Click(object sender, EventArgs e)
{
double weeklySalary = 0.00;
double hourlySalary = double.Parse(txtHourlySalary.Text);
double timeWorked = double.Parse(txtTimeWorked.Text);
weeklySalary = hourlySalary * timeWorked;
if( chkPaidOvertime.Checked)
{
if( timeWorked > 40.00 )
{
double overtime = timeWorked - 40.00;
double overtimePay = hourlySalary * 1.50 * overtime;
weeklySalary = (hourlySalary * 40.00) + overtimePay;
}
}
txtWeeklySalary.Text = weeklySalary.ToString("F");
}
</script>
<html>
<head runat="server">
<title>Payroll Preparation</title>
</head>
<body>
<form id="frmPayroll" runat="server">
<div>
<h3>Payroll Preparation</h3>
<table border=0>
<tr>
<td style="text-align: left">
<asp:Label id="lblHourlySalary" runat="server" Text="Hourly Salary:"></asp:Label>
</td>
<td style="text-align: left">
<asp:TextBox id="txtHourlySalary" Width="75px"
text="0.00" runat="server" /></td>
</tr>
<tr>
<td style="text-align: left">
<asp:Label id="lblTimeWorked" runat="server" Text="Time Worked:"></asp:Label></td>
<td style="text-align: left">
<asp:TextBox id="txtTimeWorked" text="0.00" runat="server" Width="75px" />
</td>
</tr>
<tr>
<td style="text-align: left">
</td>
<td style="text-align: left">
<asp:CheckBox ID="chkPaidOvertime" runat="server" Text="Paid Overtime" />
</td>
</tr>
<tr>
<td style="text-align: left">
</td>
<td style="text-align: left">
<asp:Button id="btnCalculate"
text="Calculate"
runat="server" OnClick="btnCalculate_Click"></asp:Button></td>
</tr>
<tr>
<td style="text-align: left">
<asp:Label id="lblWeeklySalary" runat="server" Text="Weekly Salary:"></asp:Label></td>
<td style="text-align: left">
<asp:TextBox id="txtWeeklySalary" text="0.00" Width="75px" runat="server" /></td>
</tr>
</table>
</div>
</form>
</body>
</html>Here is an example of running the program:
Likewise, one conditional statement can be placed inside another, and that nested statement can even be contained within yet another condition.
Boolean Conjunctions#
When you nest one condition in another condition as in:
if condition1 is true // The first or external condition
if Condition2 is true // The second or internal condition
statement(s)you are in fact saying that "if condition1 verifies, Then if condition2 verifies, do this...". To support a simplified version of this scenario, you can use the Boolean conjunction operator, the "AND" operator, represented as &&. Its primary formula is:
condition1 && Condition2
statement(s)You must formulate each condition to produce a true or a false result. The result is as follows:
- If condition1 is true and condition2 is true, the whole expression produces a true result. Here is an example: <%@ Page Language="C#" %> <!DOCTYPE html> <html> <head runat="server"> <script runat="server"> void BtnCalculate_Click(object sender, EventArgs e) { double principal = 0.00; double commission = 0.00; int numberOfShares = int.Parse(TxtNumberOfShares.Text); double pricePerShare = double.Parse(TxtPricePerShare.Text); principal = numberOfShares * pricePerShare; if( principal >= 0.00 && principal <= 2500.00 ) commission = 26.25 + (principal * 0.0014); if( principal > 2500.00 && principal <= 6000.00 ) commission = 45.00 + (principal * 0.0054); if( principal > 6000.00 && principal <= 20000.00 ) commission = 60.00 + (principal * 0.0028); if( principal > 20000.00 && principal <= 50000.00 ) commission = 75.00 + (principal * 0.001875); if( principal > 50000.00 && principal <= 500000.00 ) commission = 131.25 + (principal * 0.0009); if (principal > 500000.00) commission = 206.25 + (principal * 0.000075); TxtPrincipal.Text = principal.ToString("F"); TxtCommission.Text = commission.ToString("F"); TxtTotalInvestment.Text = (principal + commission).ToString("F"); } </script> <style type="text/css"> #main-title { font-size: 1.28em; font-weight: bold; text-align: center; font-family: Georgia, Garamond, 'Times New Roman', Times, serif; } #tblPayroll { width: 250px; } #whole { margin: auto; width: 255px; } </style> <title>Brokerage Company</title> </head> <body> <form id="frmBrokerage" runat="server"> <div id="whole"> <p id="main-title">Brokerage Company</p> <table id="tblPayroll"> <tr> <td> <asp:Label id="LblNumberOfShares" runat="server" Text="Number of Shares:"></asp:Label> </td> <td><asp:TextBox id="TxtNumberOfShares" Width="75px" runat="server">0</asp:TextBox></td> </tr> <tr> <td> <asp:Label id="LblPricePerShare" runat="server" Text="Price Per Share:"></asp:Label> </td> <td><asp:TextBox id="TxtPricePerShare" runat="server" Width="75px">0.00</asp:TextBox></td> </tr> <tr> <td> </td> <td> <asp:Button id="BtnCalculate" runat="server" Text="Calculate" Width="85px" OnClick="BtnCalculate_Click" /> </td> </tr> <tr> <td> <asp:Label id="LblPrincipal" runat="server" Text="Principal:"></asp:Label> </td> <td><asp:TextBox id="TxtPrincipal" runat="server" Width="75px">0.00</asp:TextBox></td> </tr> <tr> <td> <asp:Label id="LblCommission" runat="server" Text="Commission:"></asp:Label> </td> <td><asp:TextBox id="TxtCommission" runat="server" Width="75px">0.00</asp:TextBox></td> </tr> <tr> <td> <asp:Label id="LblTotalInvestment" runat="server" Text="Total Investment:"></asp:Label> </td> <td><asp:TextBox id="TxtTotalInvestment" runat="server" Width="75px">0.00</asp:TextBox> </td> </tr> </table> </div> </form> </body> </html> Here is an example of using the webpage:
- If either condition1 or condition2 is false (including if both are false), the whole expression produces a false result
To make your code easier to read, it is a good idea to include each Boolean operation in its own parentheses. Here are examples:
<script runat="server">
void BtnCalculate_Click(object sender, EventArgs e)
{
double principal = 0.00;
double commission = 0.00;
int numberOfShares = int.Parse(TxtNumberOfShares.Text);
double pricePerShare = double.Parse(TxtPricePerShare.Text);
principal = numberOfShares * pricePerShare;
if( (principal >= 0.00) && (principal <= 2500.00) )
commission = 26.25 + (principal * 0.0014);
if( (principal > 2500.00) && (principal <= 6000.00) )
commission = 45.00 + (principal * 0.0054);
if( (principal > 6000.00) && (principal <= 20000.00) )
commission = 60.00 + (principal * 0.0028);
if( (principal > 20000.00) && (principal <= 50000.00) )
commission = 75.00 + (principal * 0.001875);
if( (principal > 50000.00) && (principal <= 500000.00) )
commission = 131.25 + (principal * 0.0009);
if (principal > 500000.00)
commission = 206.25 + (principal * 0.000075);
TxtPrincipal.Text = principal.ToString("F");
TxtCommission.Text = commission.ToString("F");
TxtTotalInvestment.Text = (principal + commission).ToString("F");
}
</script>Depending on your program, if two conditions are not enough, you can create as many conjunctions as you want. The formula to follow is:
condition1 && condition2 && condition3 && . . . && condition_nWhen the expression is checked, if any of the operations is false, the whole operation is false. The only time the whole operation is true is if all of the operations are true. Of course, you can nest a Boolean condition inside another conditional statement.
Boolean Disjunctions#
Introduction#
A Boolean disjunction is a combination of conditions where only one of the conditions needs to be true for the whole operation to be true. This operation is performed using the Boolean disjunction "OR" operator represented as ||. The primary formula to follow is:
condition1 || condition2The operation works as follows:
- If at least one of condition1 OR condition2 is true, the whole operation is true
- If both conditions are false, only then will the whole operation produce a false result
Here is an example:
<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
void DdlTimePeriodSelectedIndexChanged(object sender, EventArgs e)
{
if( DdlTimePeriod.SelectedIndex == 1 || DdlTimePeriod.SelectedIndex == 2 )
{
PnlLunchSpecial.Visible = false;
PnlRegularMenu.Visible = true;
}
else
{
PnlLunchSpecial.Visible = true;
PnlRegularMenu.Visible = false;
}
}
</script>
<style type="text/css">
#main-title
{
font-size: 1.28em;
font-weight: bold;
text-align: center;
font-family: Georgia, Garamond, 'Times New Roman', Times, serif;
}
#tblRestaurant { width: 500px; }
#whole
{
margin: auto;
width: 505px;
}
</style>
<html>
<head runat="server">
<title>Restaurant</title>
</head>
<body>
<form id="frmRestaurant" runat="server">
<div id="whole">
<p id="main-title">Restaurant</p>
<table id="tblRestaurant">
<tr>
<td>
<asp:Label id="LblTimePeriod" runat="server"
Text="Select Current Time Period:"></asp:Label>
</td>
<td>
<asp:DropDownList id="DdlTimePeriod" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="DdlTimePeriodSelectedIndexChanged">
<asp:ListItem>Weekday Lunch Period (11:30 AM - 03:00 PM)</asp:ListItem>
<asp:ListItem>Evening (03:00 PM - Midnight)</asp:ListItem>
<asp:ListItem>Weekend (Saturday - Sunday)</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
</table>
<asp:Panel id="PnlLunchSpecial" runat="server" Width="400px">
<h2>Lunch Special</h2>
<table class="auto-style1">
<tr>
<td>Food Item</td>
<td>Unit Price</td>
<td>Spicy?</td>
</tr>
<tr>
<td>
<asp:Label id="LblLSItem1Name" runat="server"
Text="LS01 Chicken Chow Mein"></asp:Label>
</td>
<td>
<asp:TextBox id="TxtLSItem1UnitPrice"
runat="server" Width="70px">5.65</asp:TextBox>
</td>
<td>
<asp:CheckBox id="ChkLSItem1Spicy" runat="server" />
</td>
</tr>
<tr>
<td>
<asp:Label id="LblLSItem2Name" runat="server"
Text="LS02 Sweet && Sour Pork"></asp:Label>
</td>
<td>
<asp:TextBox id="TxtLSItem2UnitPrice" runat="server"
Width="70px">5.75</asp:TextBox>
</td>
<td>
<asp:CheckBox id="ChkLSItem2Spicy" Checked="True" runat="server" />
</td>
</tr>
<tr>
<td>
<asp:Label id="LblLSItem3Name" runat="server"
Text="LS03 Sesame Chicken"></asp:Label>
</td>
<td>
<asp:TextBox id="TxtLSItem3UnitPrice" runat="server"
Width="70px">5.85</asp:TextBox>
</td>
<td>
<asp:CheckBox id="ChkLSItem3Spicy" Checked="True" runat="server" />
</td>
</tr>
</table>
</asp:Panel>
<asp:Panel id="PnlRegularMenu" runat="server" Width="400px" Visible="False">
<h1>Regular Food Menu</h1>
<table class="auto-style1">
<tr>
<td>Food Item</td>
<td>Unit Price</td>
<td>Spicy?</td>
</tr>
<tr>
<td>
<asp:Label id="LblRMItem1Name" runat="server"
Text="RM01 Chicken Mei Fun"></asp:Label>
</td>
<td>
<asp:TextBox id="TxtRMItem1UnitPrice" runat="server"
Width="70px">9.25</asp:TextBox>
</td>
<td>
<asp:CheckBox id="ChkRMItem1Spicy" runat="server" />
</td>
</tr>
<tr>
<td>
<asp:Label id="LblRMItem2Name" runat="server"
Text="RM02 Orange Chicken"></asp:Label>
</td>
<td>
<asp:TextBox id="TxtRMItem2UnitPrice" runat="server"
Width="70px">9.50</asp:TextBox>
</td>
<td>
<asp:CheckBox id="ChkRMItem2Spicy" runat="server" />
</td>
</tr>
<tr>
<td>
<asp:Label id="LblRMItem3Name" runat="server"
Text="RM03 Barbecue Spare Ribs"></asp:Label>
</td>
<td>
<asp:TextBox id="TxtRMItem3UnitPrice" runat="server"
Width="70px">14.65</asp:TextBox>
</td>
<td>
<asp:CheckBox id="ChkRMItem3Spicy" Checked="True" runat="server" />
</td>
</tr>
<tr>
<td>
<asp:Label id="LblRMItem4Name" runat="server"
Text="Chicken Chow Mein "></asp:Label>
</td>
<td>
<asp:TextBox id="TextBox1" runat="server"
Width="70px">12.25</asp:TextBox>
</td>
<td>
<asp:CheckBox id="ChkRMItem4Spicy" Checked="True" runat="server" />
</td>
</tr>
</table>
</asp:Panel>
</div>
</form>
</body>
</html>Here is an example of using the webpage:
It is a good idea to include each Boolean operation in its parentheses. Here is an example:
<script runat="server">
void DdlTimePeriodSelectedIndexChanged(object sender, EventArgs e)
{
if( (DdlTimePeriod.SelectedIndex == 1) || (DdlTimePeriod.SelectedIndex == 2) )
{
PnlLunchSpecial.Visible = false;
PnlRegularMenu.Visible = true;
}
else
{
PnlLunchSpecial.Visible = true;
PnlRegularMenu.Visible = false;
}
}
</script>You can create a conditional statement that includes as many disjunctions as you want. The formula to follow is:
condition1 || condition2 || . . . || condition_nThe rule is the same: If any one of the individual operations is true, the whole operation is true. The whole operation is false only if all of the operations are false.
Combining Conjunctions and Disjunctions#
Conjunctions and disjunctions can be used in the same expression. A conjunction (or disjunction) can be used to evaluate one sub-expression while a disjunction (or conjunction) can be used to evaluate another sub-expression. Consider the following example: As seen previously, one way you can combine conditional statements is by nesting them.
Enumerations#
Introduction#
Imagine you have a few constant natural numbers (such as 1, 4, 10, and 42) and you want to use them in you code. Sometimes you use such numbers to perform comparisons. On paper, those numbers would mean different things to different people. Instead of using such numbers, you can name them and use the names. An enumeration is a technique of creating names to be used in place of constant numbers.
Creating an Enumeration#
An enumeration is created with the type keyword, a name, the = sign and one or a list of members. Each member is in the form | followed by a name. The primary formula to create an enumeration is:
type EnumerationName = | MemberName1 | MemberName2 | MemberName_nAlternatively, each member of the enumeration can be written on its own line:
type EnumerationName =
| MemberName1
| MemberName2
| MemberName_nThe name of an enumeration usually starts with an uppercase letter. The = sign precedes the body of the enumeration. Here are two examples:
type TimeZoneInclusion = | Entirely | Split
type InterestCompounded =
| Daily
| Weekly
| Monthly
| Quarterly
| Semiannually
| AnnuallyIf the members are created on separate lines, if you want, you can indent them, but this is only an option.
Enumerations and Variables#
You can declare a variable that is based on an enumeration. As done with the other types, you don't have to specify the type of the variable. To indicate that the variable is bound to an enumeration, initialize the variable using a member of the enumeration. Here is an example:
type Compound =
| Daily
| Weekly
| Monthly
| Quarterly
| Semiannually
| Annually
let compounding = MonthlyTo add a member of an enumeration in sprintf, use %A in the placeholder.
Enumerations and Conditional Statements#
You can access any member of the enumeration in your code. This can be done in a conditional statement where you would compare your variable to members of the enumeration. Here are example:
open System
open System.Windows.Forms
type Compound =
| Daily
| Weekly
| Monthly
| Quarterly
| Semiannually
| Annually
let mutable compounding = Monthly
let compoundInterest = new Form()
compoundInterest.Text <- "Compound Interest"
compoundInterest.Width <- 300
compoundInterest.Height <- 228
let lblPrincipal = new Label()
lblPrincipal.Left <- 18
lblPrincipal.Top <- 18
lblPrincipal.Width <- 62
lblPrincipal.Text <- "Principal:"
compoundInterest.Controls.Add(lblPrincipal)
let txtPrincipal = new TextBox()
txtPrincipal.Left <- 105
txtPrincipal.Top <- 16
txtPrincipal.Width <- 84
txtPrincipal.Text <- "0.00"
compoundInterest.Controls.Add(txtPrincipal)
let lblInterestRate = new Label()
lblInterestRate.Left <- 18
lblInterestRate.Top <- 46
lblInterestRate.Width <- 80
lblInterestRate.Text <- "Interest Rate:"
compoundInterest.Controls.Add(lblInterestRate)
let txtInterestRate = new TextBox()
txtInterestRate.Left <- 105
txtInterestRate.Top <- 44
txtInterestRate.Width <- 60
txtInterestRate.Text <- "0.00"
compoundInterest.Controls.Add(txtInterestRate)
let lblPercent = new Label()
lblPercent.Left <- 165
lblPercent.Top <- 46
lblPercent.Width <- 22
lblPercent.Text <- "%"
compoundInterest.Controls.Add(lblPercent)
let lblPeriods = new Label()
lblPeriods.Left <- 18
lblPeriods.Top <- 76
lblPeriods.Width <- 62
lblPeriods.Text <- "Periods:"
compoundInterest.Controls.Add(lblPeriods)
let txtPeriods = new TextBox()
txtPeriods.Left <- 105
txtPeriods.Top <- 73
txtPeriods.Width <- 60
txtPeriods.Text <- "0"
compoundInterest.Controls.Add(txtPeriods)
let lblYears = new Label()
lblYears.Left <- 165
lblYears.Top <- 76
lblYears.Text <- "Years"
compoundInterest.Controls.Add(lblYears)
let lblCompounded = new Label()
lblCompounded.Left <- 18
lblCompounded.Top <- 106
lblCompounded.Width <- 80
lblCompounded.Text <- "Compounded:"
compoundInterest.Controls.Add(lblCompounded)
let cbxCompounded = new ComboBox()
cbxCompounded.Left <- 105
cbxCompounded.Top <- 101
cbxCompounded.Width <- 84
cbxCompounded.Items.AddRange([| "Daily"; "Weekly"; "Monthly"; "Quarterly"; "Semiannually"; "Annually" |])
cbxCompounded.Text <- "Annually"
let btnCalculate = new Button()
btnCalculate.Left <- 196
btnCalculate.Top <- 102
btnCalculate.Text <- "Calculate"
let lblInterestEarned = new Label()
lblInterestEarned.Left <- 18
lblInterestEarned.Top <- 135
lblInterestEarned.Width <- 85
lblInterestEarned.Text <- "Interest Earned:"
compoundInterest.Controls.Add(lblInterestEarned)
let txtInterestEarned = new TextBox()
txtInterestEarned.Left <- 105
txtInterestEarned.Top <- 132
txtInterestEarned.Width <- 84
txtInterestEarned.Text <- "0.00"
compoundInterest.Controls.Add(txtInterestEarned)
let lblFutureValue = new Label()
lblFutureValue.Left <- 18
lblFutureValue.Top <- 160
lblFutureValue.Width <- 80
lblFutureValue.Text <- "Future Value:"
compoundInterest.Controls.Add(lblFutureValue)
let txtFutureValue = new TextBox()
txtFutureValue.Left <- 105
txtFutureValue.Top <- 160
txtFutureValue.Width <- 84
txtFutureValue.Text <- "0.00"
compoundInterest.Controls.Add(txtFutureValue)
let btnClose = new Button()
btnClose.Left <- 196
btnClose.Top <- 156
btnClose.Width <- 75
btnClose.Text <- "Close"
let cbxCompoundedSelectedIndexChanged(e) =
if cbxCompounded.Text = "Daily" then
compounding <- Daily
elif cbxCompounded.Text = "Weekly" then
compounding <- Weekly
elif cbxCompounded.Text = "Monthly" then
compounding <- Monthly
elif cbxCompounded.Text = "Quarterly" then
compounding <- Quarterly
elif cbxCompounded.Text = "Semiannually" then
compounding <- Semiannually
else // if(cbxCompounded.Text = "Annually")
compounding <- Annually
cbxCompounded.SelectedIndexChanged.Add(cbxCompoundedSelectedIndexChanged)
compoundInterest.Controls.Add(cbxCompounded)
let btnCalculateClick(e) =
let mutable compoundFrequency = 0.00
let principal = float txtPrincipal.Text
let interestRate = (float txtInterestRate.Text) / 100.00
let periods = float txtPeriods.Text
if compounding = Daily then
compoundFrequency <- 365.00
elif compounding = Weekly then
compoundFrequency <- 52.00
elif compounding = Monthly then
compoundFrequency <- 12.00
elif compounding = Quarterly then
compoundFrequency <- 4.00
elif compounding = Semiannually then
compoundFrequency <- 2.00
else // if compounding = Annually then
compoundFrequency <- 1.00
let futureValue = principal * ((1.00 + (interestRate / compoundFrequency)) ** compoundFrequency * periods)
let interestEarned = futureValue - principal
txtInterestEarned.Text <- (sprintf "%0.02f" interestEarned)
txtFutureValue.Text <- (sprintf "%0.02f" futureValue)
btnCalculate.Click.Add(btnCalculateClick)
compoundInterest.Controls.Add(btnCalculate)
let btnCloseClick(e) = compoundInterest.Close()
btnClose.Click.Add(btnCloseClick)
compoundInterest.Controls.Add(btnClose)
Application.Run(compoundInterest)Here is an example of running the program:
Remember that you can specify the data type of a variable by following its name with a colon and the data type. This can be done as follows for an enumeration:
type Compound =
| Daily
| Weekly
| Monthly
| Quarterly
| Semiannually
| Annually
let compounding : Compound = MonthlyFurthermore, to refer to a member of an enumeration and to make your code easier to read, you can qualify each member of an enumeration. This is done by preceding the name of the member of the enumeration with the name of the enumeration separated by a period. Here are examples:
let cbxCompoundedSelectedIndexChanged(e) =
if cbxCompounded.Text = "Daily" then
compounding <- Compound.Daily
elif cbxCompounded.Text = "Weekly" then
compounding <- Compound.Weekly
elif cbxCompounded.Text = "Monthly" then
compounding <- Compound.Monthly
elif cbxCompounded.Text = "Quarterly" then
compounding <- Compound.Quarterly
elif cbxCompounded.Text = "Semiannually" then
compounding <- Compound.Semiannually
else
compounding <- Compound.Annually
cbxCompounded.SelectedIndexChanged.Add(cbxCompoundedSelectedIndexChanged)
compoundInterest.Controls.Add(cbxCompounded)
let btnCalculateClick(e) =
let mutable compoundFrequency = 0.00
let principal = float txtPrincipal.Text
let interestRate = (float txtInterestRate.Text) / 100.00
let periods = float txtPeriods.Text
if compounding = Compound.Daily then
compoundFrequency <- 365.00
elif compounding = Compound.Weekly then
compoundFrequency <- 52.00
elif compounding = Compound.Monthly then
compoundFrequency <- 12.00
elif compounding = Compound.Quarterly then
compoundFrequency <- 4.00
elif compounding = Compound.Semiannually then
compoundFrequency <- 2.00
else // if compounding = Compound.Annually then
compoundFrequency <- 1.00
let futureValue = principal * ((1.00 + (interestRate / compoundFrequency)) ** compoundFrequency * periods)
let interestEarned = futureValue - principal
txtInterestEarned.Text <- (sprintf "%0.02f" interestEarned)
txtFutureValue.Text <- (sprintf "%0.02f" futureValue)The Values of Members of an Enumeration#
An enumeration contains members whose names actually represent constant values. The numeric values can be anything you want. In fact, you can specify the value of each member as you want. To do this, assign the desired number to each member of the enumeration. The formulat to use is:
type EnumerationName =
| MemberName1 [ = IntegralValue1 ]
| MemberName2 [ = IntegralValue2 ] ]
| MemberName_n [ = IntegralValue_n ]As you saw in the beginning, you don't have to specify the values of the members of an enumeration; but unlike other languages such as C/C++ or C#, if you decide to give values, you must assign a number to each member of the enumeration. Here are examples:
type Category =
| Teen = 10
| Adult = 20
| Senior = 30As you saw in the beginning, you don't have to specify the values of the members of an enumeration; but unlike other languages such as C/C++ or C#, if you decide to give values, you must assign a number to each member of the enumeration. After specifying the values of members of the enumeration, whenever you want to use a member of that enumeration in your code, you must qualify that member. Here are examples:
open System
open System.Windows.Forms
type Compound =
| Daily = 365
| Weekly = 52
| Monthly = 12
| Quarterly = 4
| Semiannually = 2
| Annually = 1
let mutable compounding = Compound.Monthly
let compoundInterest = new Form()
compoundInterest.Text <- "Compound Interest"
compoundInterest.Width <- 300
compoundInterest.Height <- 228
let lblPrincipal = new Label()
lblPrincipal.Left <- 18
lblPrincipal.Top <- 18
lblPrincipal.Width <- 62
lblPrincipal.Text <- "Principal:"
compoundInterest.Controls.Add(lblPrincipal)
let txtPrincipal = new TextBox()
txtPrincipal.Left <- 105
txtPrincipal.Top <- 16
txtPrincipal.Width <- 84
txtPrincipal.Text <- "0.00"
compoundInterest.Controls.Add(txtPrincipal)
let lblInterestRate = new Label()
lblInterestRate.Left <- 18
lblInterestRate.Top <- 46
lblInterestRate.Width <- 80
lblInterestRate.Text <- "Interest Rate:"
compoundInterest.Controls.Add(lblInterestRate)
let txtInterestRate = new TextBox()
txtInterestRate.Left <- 105
txtInterestRate.Top <- 44
txtInterestRate.Width <- 60
txtInterestRate.Text <- "0.00"
compoundInterest.Controls.Add(txtInterestRate)
let lblPercent = new Label()
lblPercent.Left <- 165
lblPercent.Top <- 46
lblPercent.Width <- 22
lblPercent.Text <- "%"
compoundInterest.Controls.Add(lblPercent)
let lblPeriods = new Label()
lblPeriods.Left <- 18
lblPeriods.Top <- 76
lblPeriods.Width <- 62
lblPeriods.Text <- "Periods:"
compoundInterest.Controls.Add(lblPeriods)
let txtPeriods = new TextBox()
txtPeriods.Left <- 105
txtPeriods.Top <- 73
txtPeriods.Width <- 60
txtPeriods.Text <- "0"
compoundInterest.Controls.Add(txtPeriods)
let lblYears = new Label()
lblYears.Left <- 165
lblYears.Top <- 76
lblYears.Text <- "Years"
compoundInterest.Controls.Add(lblYears)
let lblCompounded = new Label()
lblCompounded.Left <- 18
lblCompounded.Top <- 106
lblCompounded.Width <- 80
lblCompounded.Text <- "Compounded:"
compoundInterest.Controls.Add(lblCompounded)
let cbxCompounded = new ComboBox()
cbxCompounded.Left <- 105
cbxCompounded.Top <- 101
cbxCompounded.Width <- 84
cbxCompounded.Items.AddRange([| "Daily"; "Weekly"; "Monthly"; "Quarterly"; "Semiannually"; "Annually" |])
cbxCompounded.Text <- "Annually"
let btnCalculate = new Button()
btnCalculate.Left <- 196
btnCalculate.Top <- 100
btnCalculate.Text <- "Calculate"
let lblInterestEarned = new Label()
lblInterestEarned.Left <- 18
lblInterestEarned.Top <- 135
lblInterestEarned.Width <- 85
lblInterestEarned.Text <- "Interest Earned:"
compoundInterest.Controls.Add(lblInterestEarned)
let txtInterestEarned = new TextBox()
txtInterestEarned.Left <- 105
txtInterestEarned.Top <- 132
txtInterestEarned.Width <- 84
txtInterestEarned.Text <- "0.00"
compoundInterest.Controls.Add(txtInterestEarned)
let lblFutureValue = new Label()
lblFutureValue.Left <- 18
lblFutureValue.Top <- 160
lblFutureValue.Width <- 80
lblFutureValue.Text <- "Future Value:"
compoundInterest.Controls.Add(lblFutureValue)
let txtFutureValue = new TextBox()
txtFutureValue.Left <- 105
txtFutureValue.Top <- 160
txtFutureValue.Width <- 84
txtFutureValue.Text <- "0.00"
compoundInterest.Controls.Add(txtFutureValue)
let btnClose = new Button()
btnClose.Left <- 196
btnClose.Top <- 158
btnClose.Width <- 75
btnClose.Text <- "Close"
let cbxCompoundedSelectedIndexChanged(e) =
if cbxCompounded.Text = "Daily" then
compounding <- Compound.Daily
elif cbxCompounded.Text = "Weekly" then
compounding <- Compound.Weekly
elif cbxCompounded.Text = "Monthly" then
compounding <- Compound.Monthly
elif cbxCompounded.Text = "Quarterly" then
compounding <- Compound.Quarterly
elif cbxCompounded.Text = "Semiannually" then
compounding <- Compound.Semiannually
else // if(cbxCompounded.Text = "Annually")
compounding <- Compound.Annually
cbxCompounded.SelectedIndexChanged.Add(cbxCompoundedSelectedIndexChanged)
compoundInterest.Controls.Add(cbxCompounded)
let btnCalculateClick(e) =
let mutable compoundFrequency = 0.00
let principal = float txtPrincipal.Text
let interestRate = (float txtInterestRate.Text) / 100.00
let periods = float txtPeriods.Text
if compounding = Compound.Daily then
compoundFrequency <- 365.00
elif compounding = Compound.Weekly then
compoundFrequency <- 52.00
elif compounding = Compound.Monthly then
compoundFrequency <- 12.00
elif compounding = Compound.Quarterly then
compoundFrequency <- 4.00
elif compounding = Compound.Semiannually then
compoundFrequency <- 2.00
else // if compounding = Annually then
compoundFrequency <- 1.00
let futureValue = principal * ((1.00 + (interestRate / compoundFrequency)) ** compoundFrequency * periods)
let interestEarned = futureValue - principal
txtInterestEarned.Text <- (sprintf "%0.02f" interestEarned)
txtFutureValue.Text <- (sprintf "%0.02f" futureValue)
btnCalculate.Click.Add(btnCalculateClick)
compoundInterest.Controls.Add(btnCalculate)
let btnCloseClick(e) = compoundInterest.Close()
btnClose.Click.Add(btnCloseClick)
compoundInterest.Controls.Add(btnClose)
Application.Run(compoundInterest)Remember that you can assign any value you want to each member of the enumeration but the values must be integers or characters of type sbyte, byte, int16, uint16, int32, uint32, int64, uint16, uint64, or char.
Conditional Switches#
Case Switches#
Introduction#
When defining an expression whose result would lead to a specific program execution, the switch statement considers that result and executes a statement based on the possible outcome of that expression, this possible outcome is called a case. The different outcomes are listed in the body of the switch statement and each case has its own execution, if necessary. The body of a switch statement is delimited from an opening to a closing curly brackets: "{" to "}"ÃÂ. The syntax of the switch statement is:
switch(Expression)
{
case Choice1:
Statement1;
break;
case Choice2:
Statement2;
break;
case Choice-n:
Statement-n;
break;
}In C++, you can omit the break keyword in a case. This creates the "fall through" effect as follows: after code executes in a case, if nothing "stops" it, the execution continues to the next case. This has caused problems and confusing execution in the past in some C++ programs. To avoid it, C# requires code interruption at the end of every case. This interruption is done using the break keyword.
The value analyzed in a case statement must be an integer. Since enumeration members are essentially natural numbers, you can use an enum member as the expression for a switch statement.
using System;
public enum HouseType
{
Unknown,
SingleFamily,
Townhouse,
Condominium
}
public class Exercise
{
public static int Main()
{
var type = HouseType.Unknown;
var choice = 0;
var garage = "";
Response.Write("Enter the type of house you want to purchase");
Response.Write("1. Single Family");
Response.Write("2. Townhouse");
Response.Write("3. Condominium");
Response.Write("You Choice? ");
choice = int.Parse(Console.ReadLine());
switch (choice)
{
case 1:
type = HouseType.SingleFamily;
break;
case 2:
type = HouseType.Townhouse;
break;
case 3:
type = HouseType.Condominium;
break;
}
Response.Write("Does the house have an indoor garage (1=Yes/0=No)? ");
var answer = int.Parse(Console.ReadLine());
if (answer == 1)
garage = "Yes";
else
garage = "No";
Response.Write("\nDesired House Type: {0}", type);
Response.Write("Has indoor garage? {0}", garage);
return 0;
}
}When establishing the possible outcomes that the switch statement should consider, at times there will be possibilities other than those listed and you will be likely to consider them. This special case is handled by the default keyword. The default case would be considered if none of the listed cases matches the supplied answer. The syntax of the switch statement that considers the default case would be:
switch(Expression)
{
case Choice1:
Statement1;
break;
case Choice2:
Statement2;
break;
case Choice-n:
Statement-n;
break;
default:
Other-Possibility;
break;
}In C++, the default section doesn't need a break keyword because it is the last. In C#, every case and the default section must have its own exit mechanism, which is taken care of by a break keyword.
Therefore another version of the program above would be
using System;
public enum HouseType
{
Unknown,
SingleFamily,
Townhouse,
Condominium
}
public class Exercise
{
public static int Main()
{
var type = HouseType.Unknown;
var choice = 0;
var garage = "";
Response.Write("Enter the type of house you want to purchase");
Response.Write("1. Single Family");
Response.Write("2. Townhouse");
Response.Write("3. Condominium");
Response.Write("You Choice? ");
choice = int.Parse(Console.ReadLine());
switch (choice)
{
case 1:
type = HouseType.SingleFamily;
break;
case 2:
type = HouseType.Townhouse;
break;
case 3:
type = HouseType.Condominium;
break;
default:
type = HouseType.Unknown;
break;
}
Response.Write("Does the house have an indoor garage (1=Yes/0=No)? ");
var answer = int.Parse(Console.ReadLine());
if (answer == 1)
garage = "Yes";
else
garage = "No";
Response.Write("\nDesired House Type: {0}", type);
Response.Write("Has indoor garage? {0}", garage);
return 0;
}
}Here is an example of running the program:
Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 8
Does the house have an indoor garage (1=Yes/0=No)? 2
Desired House Type: Unknown
Has indoor garage? No
Press any key to continue . . .Besides a value of an int type, you can also use another variant of integers on a switch statement. For example, you can use letters to validate the cases. Here is an example:
using System;
public enum HouseType
{
Unknown,
SingleFamily,
Townhouse,
Condominium
}
public class Exercise
{
public static int Main()
{
var type = HouseType.Unknown;
var choice = 0;
var garage = "";
Response.Write("Enter the type of house you want to purchase");
Response.Write("1. Single Family");
Response.Write("2. Townhouse");
Response.Write("3. Condominium");
Response.Write("You Choice? ");
choice = int.Parse(Console.ReadLine());
switch (choice)
{
case 1:
type = HouseType.SingleFamily;
break;
case 2:
type = HouseType.Townhouse;
break;
case 3:
type = HouseType.Condominium;
break;
default:
type = HouseType.Unknown;
break;
}
Response.Write("Does the house have an indoor garage (y/n)? ");
var answer = char.Parse(Console.ReadLine());
switch (Answer)
{
case 'y':
garage = "Yes";
break;
case 'Y':
garage = "Yes";
break;
case 'n':
garage = "No";
break;
case 'N':
garage = "No";
break;
default:
garage = "Not Specified";
break;
}
Response.Write("\nDesired House Type: {0}", type);
Response.Write("Has indoor garage? {0}", garage);
return 0;
}
}Here is an example of running the program:
Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 3
Does the house have an indoor garage (y/n)? y
Desired House Type: Condominium
Has indoor garage? Yes
Press any key to continue . . .Application: Introducing Conditional Switches
- Start Microsoft Visual Studio
- To create a new application, on the main menu, click FILE -> New -> Project...
- In the middle list, click Empty Project
- Change the Name to NationalBank3 and press Enter
- To create a new file, on the main menu, click PROJECT -> Add New Item...
- In the middle list, click Code File
- Change the Name of the file to Customer
- Click Add
- Complete the Customer.cs file as follows: public enum AccountType { Checking, Saving, Other } public class Customer { public string AccountNumber; public AccountType Type; public string FullName; public double Balance; public short PIN; public Customer(string acnt = "000-000000-000", AccountType category = AccountType.Other, string name = "John Doe") { AccountNumber = acnt; Type = category; FullName = name; PIN = 0; Balance = 0.00D; } }
- To create a new file, in the Solution Explorer, right-click NationalBank3 -> Add -> New Item...
- In the middle list, make sure Code File is selected. Change the Name to Management and press Enter
- Complete the file as follows: using System; public class Management { private Customer CreateNewAccount() { byte typeOfAccount = 0; Customer client = new Customer(); Response.Write("==========================================="); Response.Write("==-= National Bank =-======================"); Response.Write("-------------------------------------------"); Response.Write("Enter a number for the new account(000-000000-000): "); client.AccountNumber = Console.ReadLine(); Response.Write("What type of account the customer wants to open"); Response.Write("1 - Checking Account"); Response.Write("2 - Savings Account"); Response.Write("Enter account type: "); typeOfAccount = byte.Parse(Console.ReadLine()); if (typeOfAccount == 1) client.Type = AccountType.Checking; else if (typeOfAccount == 2) client.Type = AccountType.Saving; else client.Type = AccountType.Other; Response.Write("Enter customer name: "); client.FullName = Console.ReadLine(); Response.Write("Ask the customer to enter a PIN: "); client.PIN = short.Parse(Console.ReadLine()); return client; } public double GetMoney() { double amount = 0; Response.Write("Amount: "); amount = double.Parse(Console.ReadLine()); return amount; } private void ShowAccountInformation(Customer cust) { Response.Write("==========================================="); Response.Write("==-= National Bank =-======================"); Response.Write("Customer Account Information"); Response.Write("-------------------------------------------"); Response.Write("Account #: {0}", cust.AccountNumber); Response.Write("Account Type: {0}", cust.Type); Response.Write("Full Name: {0}", cust.FullName); Response.Write("PIN #: {0}", cust.PIN); Response.Write("Balance: {0:F}", cust.Balance); Response.Write("==========================================="); } public static int Main() { double amount = 0; byte nextAction = 0; Customer accountHolder = null; Management registration = new Management(); Console.Title = "National Bank"; accountHolder = registration.CreateNewAccount(); Response.Write("Enter the customer's initial deposit"); accountHolder.Balance = registration.GetMoney(); Console.Clear(); registration.ShowAccountInformation(accountHolder); Response.Write("What do you want to do now?"); Response.Write("1 - Check account balance"); Response.Write("2 - Make a deposit"); Response.Write("3 - Withdraw money"); Response.Write("4 - Transfer money from one account to another"); nextAction = byte.Parse(Console.ReadLine()); switch (nextAction) { case 1: break; case 2: Response.Write("Enter the Deposit "); amount = double.Parse(Console.ReadLine()); accountHolder.Balance = accountHolder.Balance + amount; break; case 3: Response.Write("Enter the Withdrawal "); amount = double.Parse(Console.ReadLine()); accountHolder.Balance = accountHolder.Balance - amount; break; case 4: Response.Write("Operation not available: You have only one account with us"); break; } Console.Clear(); registration.ShowAccountInformation(accountHolder); Console.ReadKey(); return 0; } }
- Press F5 to execute
- Enter information as follows: Account # 202-410443-240 Account Type: 1 Customer Name: Paul Martin Eloundou PIN: 8402 Initial Deposit: 750 =========================================== ==-= National Bank =-====================== ------------------------------------------- Enter a number for the new account(000-000000-000)202-410443-240 What type of account the customer wants to open 1 - Checking Account 2 - Savings Account Enter account type: 1 Enter customer name: Paul Martin Eloundou Ask the customer to enter a PIN: 8402 Enter the customer's initial deposit Amount: 750
- Press Enter =========================================== ==-= National Bank =-====================== Customer Account Information ------------------------------------------- Account #: 202-410443-240 Account Type: Checking Full Name: Paul Martin Eloundou PIN #: 8402 Balance: 750.00 =========================================== What do you want to do now? 1 - Check account balance 2 - Make a deposit 3 - Withdraw money 4 - Transfer money from one account to another
- When asked for the next action, type 2 and press Enter
- Type the amount as 226.85 and press Enter
- Press Enter to close the DOS window and return to your programming environment
Combining Cases#
Each of the cases we have used so far examined only one possibility before executing the corresponding statement. You can combine cases to execute the same statement. To do this, type a case, its value, and the semi-colon. Type another case using the same formula. When the cases are ready, you can then execute the desired statement. Here is an example:
using System;
public enum HouseType
{
Unknown,
SingleFamily,
Townhouse,
Condominium
}
public class Exercise
{
public static int Main()
{
var type = HouseType.Unknown;
var choice = 0;
var garage = "";
Response.Write("Enter the type of house you want to purchase");
Response.Write("1. Single Family");
Response.Write("2. Townhouse");
Response.Write("3. Condominium");
Response.Write("You Choice? ");
choice = int.Parse(Console.ReadLine());
switch (choice)
{
case 1:
type = HouseType.SingleFamily;
break;
case 2:
type = HouseType.Townhouse;
break;
case 3:
type = HouseType.Condominium;
break;
default:
type = HouseType.Unknown;
break;
}
Response.Write("Does the house have an indoor garage (y/n)? ");
var answer = char.Parse(Console.ReadLine());
switch (answer)
{
case 'y':
case 'Y':
garage = "Yes";
break;
case 'n':
case 'N':
garage = "No";
break;
default:
garage = "Not Specified";
break;
}
Response.Write("\nDesired House Type: {0}", type);
Response.Write("Has indoor garage? {0}", garage);
return 0;
}
}This would produce:
Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 3
Does the house have an indoor garage (y/n)? Y
Desired House Type: Condominium
Has indoor garage? Yes
Press any key to continue . . .Using Enumerations#
One of the most fundamental uses of enumerations is to process them in a switch statement. To do this, you pass the value of an enumeration to a switch. The values of the enumerations are then processed in the case statements. Here is an example:
using System;
public enum HouseType
{
Unknown,
SingleFamily,
Townhouse,
Condominium
}
public class Exercise
{
public static int Main()
{
var PropertyType = "";
var choice = 0;
var garage = "";
Response.Write("Enter the type of house you want to purchase");
Response.Write("1. Single Family");
Response.Write("2. Townhouse");
Response.Write("3. Condominium");
Response.Write("You Choice? ");
choice = int.Parse(Console.ReadLine());
switch ((HouseType)choice)
{
case HouseType.SingleFamily:
PropertyType = "Single Family";
break;
case HouseType.Townhouse:
PropertyType = "Townhouse";
break;
case HouseType.Condominium:
PropertyType = "Condominium";
break;
default:
PropertyType = "Unknown";
break;
}
Response.Write("Does the house have an indoor garage (y/n)? ");
var answer = char.Parse(Console.ReadLine());
switch (answer)
{
case 'y':
case 'Y':
garage = "Yes";
break;
case 'n':
case 'N':
garage = "No";
break;
default:
garage = "Not Specified";
break;
}
Response.Write("\nDesired House Type: {0}", PropertyType);
Response.Write("Has indoor garage? {0}", garage);
return 0;
}
}Here is an example of running the program:
Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 1
Does the house have an indoor garage (y/n)? N
Desired House Type: Single Family
Has indoor garage? No
Press any key to continue . . .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;
Response.Write("Enter the type of house you want to purchase");
Response.Write("1. Single Family");
Response.Write("2. Townhouse");
Response.Write("3. Condominium");
Response.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;
Response.Write("Up to how much can you afford? $");
value = double.Parse(Console.ReadLine());
Response.Write("\nDesired House Type: {0}", type);
Response.Write("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:
- The house is single family
- 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;
Response.Write("Enter the type of house you want to purchase");
Response.Write("1. Single Family");
Response.Write("2. Townhouse");
Response.Write("3. Condominium");
Response.Write("You Choice? ");
choice = int.Parse(Console.ReadLine());
Response.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;
Response.Write("\nDesired House Type: {0}", type);
Response.Write("Maximum value afforded: {0:C}", value);
if (type == HouseType.SingleFamily && value <= 550000)
Response.Write("\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) )
Response.Write("\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;
Response.Write("Enter the type of house you want to purchase");
Response.Write("1. Single Family");
Response.Write("2. Townhouse");
Response.Write("3. Condominium");
Response.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;
Response.Write("Up to how much can you afford? $");
value = decimal.Parse(Console.ReadLine());
Response.Write("\nDesired House Type: {0}", type);
Response.Write("Maximum value afforded: {0:C}", value);
if (type == HouseType.SingleFamily && value <= 550000)
Response.Write("\nDesired House Matched");
else
Response.Write("\nThe House Doesn't Match the Desired Criteria");
/* Can also be written as follows:
Response.Write((type == HouseType.SingleFamily && value <= 550000) ? "\nDesired House Matched" : "\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:
- The house is a single family home
- The house costs less than $450,001
- 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;
Response.Write("Enter the type of house you want to purchase");
Response.Write("1. Single Family");
Response.Write("2. Townhouse");
Response.Write("3. Condominium");
Response.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;
Response.Write("Up to how much can you afford? $");
value = double.Parse(Console.ReadLine());
Response.Write("Does the house have an indoor garage (1=Yes/0=No)? ");
int ans = int.Parse(Console.ReadLine());
Response.Write("\nDesired House Type: {0}", type);
Response.Write("Maximum value afforded: {0:C}", value);
Response.Write("House has indoor garage: ");
if (ans == 1)
Response.Write("Yes");
else
Response.Write("No");
if ((type == HouseType.SingleFamily) && (value <= 550000) && (ans == 1))
Response.Write("\nDesired House Matched");
else
Response.Write("\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:
- The property is a condominium
- 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;
Response.Write("Enter the type of house you want to purchase");
Response.Write("1. Single Family");
Response.Write("2. Townhouse");
Response.Write("3. Condominium");
Response.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;
Response.Write("How many stories? ");
stories = int.Parse(Console.ReadLine());
Response.Write("\nDesired House Type: {0}", type);
Response.Write("Number of Stories: {0}", stories);
if ((type == HouseType.Condominium) || (stories == 1))
Response.Write("\nDesired House Matched");
else
Response.Write("\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#
In contrast to checking only two conditions, you might encounter a scenario with three requirements where you need to verify if at least one is true.
- Close your programming environment
- When asked whether you want to save, click No
Previous Copyright © 2008-2016, FunctionX Next

