Introduction to Conditions
When interacting with a computer, a user submits values to a running application. Some of these values are valid. Some other values must be rejected or…
Boolean Variables#
Introduction#
When interacting with a computer, a user submits values to a running application. Some of these values are valid. Some other values must be rejected or changed. To take care of these, the values must be checked, examined, re-examined, etc. The validity of a value is checked against its type. For example, a number can be checked as being equal to another. A condition can be checked as being true. A measure can be checked as to whether it is higher than a certain threshold. To perform the necessary validations of values, the C# language provides some symbols, referred to as Boolean operators. Application: Introducing Boolean Variables
- 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 FlowerShop1 and press Enter
- To create a new class, in the Class View, right-click FlowerShop1 -> Add -> Class...
- Set the Name of the class to Flower and click Add
- Complete the Flower.cs file as follows: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FlowerShop1 { public class Flower { public int typeOfFlower; public int majorColor; public char arrangement; public decimal unitPrice; public Flower() { typeOfFlower = 0; majorColor = 0; arrangement = 'B'; unitPrice = 0.00M; } public Flower(int type) { typeOfFlower = type; majorColor = 0; arrangement = 'B'; unitPrice = 0.00M; } public Flower(int tp, int clr, char argn, decimal price) { typeOfFlower = tp; majorColor = clr; arrangement = argn; unitPrice = price; } } }
- To create a new class, in the Class View, right-click FlowerShop1 -> Add -> click Class...
- Set the Name of the class to OrderProcessing and click Add
- Complete the OrderProcessing.cs file as follows: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FlowerShop1 { public class OrderProcessing { public OrderProcessing() { flowerOrder = new Flower(); } public Flower flowerOrder; public int quantity; public decimal GetTotalPrice() { return quantity * flowerOrder.unitPrice; } } }
- To create a new file, in the Solution Explorer, right-click FlowerShop1 -> Add -> New Item...
- In the middle list, click Code File
- Change the Name to FlowerShop and press Enter
- Complete the file as follows: using System; using FlowerShop1; public class Program { private static OrderProcessing CreateFlowerOrder() { OrderProcessing order = new OrderProcessing(); int type, color, qty; char arrangement; decimal price; Console.WriteLine("======================="); Console.WriteLine("==-=-=Flower Shop=-=-=="); Console.WriteLine("-----------------------"); Console.WriteLine("Enter the Type of Flower Order"); Console.WriteLine("1. Roses"); Console.WriteLine("2. Lilies"); Console.WriteLine("3. Daisies"); Console.WriteLine("4. Carnations"); Console.WriteLine("5. Live Plant"); Console.WriteLine("6. Mixed"); Console.Write("Your Choice: "); type = int.Parse(Console.ReadLine()); Console.WriteLine("Enter the Color"); Console.WriteLine("1. Red"); Console.WriteLine("2. White"); Console.WriteLine("3. Yellow"); Console.WriteLine("4. Pink"); Console.WriteLine("5. Orange"); Console.WriteLine("6. Blue"); Console.WriteLine("7. Lavender"); Console.WriteLine("8. Mixed"); Console.Write("Your Choice: "); color = int.Parse(Console.ReadLine()); Console.WriteLine("Enter the Type of Arrangement"); Console.WriteLine("U. Bouquet"); Console.WriteLine("V. Vase"); Console.WriteLine("B. Basket"); Console.WriteLine("M. Mixed"); Console.Write("Your Choice: "); arrangement = char.Parse(Console.ReadLine()); Console.Write("Enter the Unit Price: "); price = decimal.Parse(Console.ReadLine()); Console.Write("Enter Quantity: "); qty = int.Parse(Console.ReadLine()); Flower flr = new Flower(type, color, arrangement, price); order.flowerOrder = flr; order.quantity = qty; return order; } private static void ShowFlowerOrder(OrderProcessing order) { Console.WriteLine("======================="); Console.WriteLine("==-=-=Flower Shop=-=-=="); Console.WriteLine("-----------------------"); Console.WriteLine("Flower Type: {0}", order.flowerOrder.typeOfFlower); Console.WriteLine("Flower Color: {0}", order.flowerOrder.majorColor); Console.WriteLine("Arrangement: {0}", order.flowerOrder.arrangement); Console.WriteLine("Price: {0:C}", order.flowerOrder.unitPrice); Console.WriteLine("Quantity: {0}", order.quantity); Console.WriteLine("Total Price: {0:C}", order.GetTotalPrice()); Console.WriteLine("======================="); } public static int Main() { Console.Title = "Corner Stone Flower Shop"; OrderProcessing flower = CreateFlowerOrder(); Console.Clear(); ShowFlowerOrder(flower); System.Console.ReadKey(); return 0; } }
- To debug the application, on the main menu, click Debug -> Step Into
- Move the windows to make sure you can see Microsoft Visual Studio, its Locals window, and the DOS window
- Press F8 three times and observe the list of variables in the Locals window
- Press F8 twice
- In the Locals window, click the + button on this to expand it
- Press F8 twice
- In the Locals window, click the + button on this to expand it
- Press F8 continually until the OrderProcessing.cs file displays again
- Press F8
- In the Locals window, click the + button of flowerOrder to expand it
- In the Locals window, click the + button on this to expand it
- Press F8. Check the list of variables and their values in the Locals window
- In the Locals window, click the + button of order to expand it
- Click the + button of flowerOrder to expand it
- Press F8 continually and observe the line being written to the DOS
- When the DOS window receives focus, for the type of flower, enter 4 and press Enter
- When Microsoft Visual Studio receives focus, press F8 continually until the DOS window receives focus
- For the color, type 6 and press Enter
- When Microsoft Visual Studio receives focus, press F8 continually until the DOS window receives focus
- For the type of flower arrangement, type v and press Enter
- When Microsoft Visual Studio receives focus, press F8 twice until the DOS window receives focus
- For the price, type 37.95 and press Enter
- When Microsoft Visual Studio receives focus, press F8 twice until the DOS window receives focus
- For the quantity, type 2 and press Enter
- Press F8 twice
- In the Locals window, click the + button on this to expand it
- Press F8 continually and observe in the Locals window how the variables are receiving new values
- In the Locals window, click the + button of order to expand it
- Click the + button of flowerOrder to expand it
- Press F8
- In the Locals window, click the + button on flr to expand it
- Continually press F8 and observe the changing values in the Locals window
- Continually press F8 and see the lines being written in the DOS window ======================= ==-=-=Flower Shop=-=-== ----------------------- Flower Type: 4 Flower Color: 6 Arrangement: V Price: $37.95 Quantity: 2 Total Price: $75.90 =======================
Declaring a Boolean Variable#
A variable is referred to as Boolean if it can hold a value that is either true or false. To declare a Boolean variable, you can use either the var or the bool keyword. Here is an example:
using System;
public class Exercise
{
static int Main()
{
bool drinkingUnderAge;
return 0;
}
}Alternatively, you can declare a Boolean variable using the Boolean data type. The Boolean data type is part of the System namespace. Here is an example:
using System;
public class Exercise
{
static int Main()
{
bool drinkingUnderAge;
Boolean theFloorIsCoveredWithCarpet;
return 0
}
}After the variable has been declared, you must initialize it with a true or a false value. In fact, if you declare it as var, you must initialize it. Here is an example:
using System;
public class Exercise
{
static int Main()
{
var drinkingUnderAge = true;
return 0;
}
}To display the value of a Boolean variable on the console, you can type its name in the parentheses of the Write() or the WriteLine() methods of the Console class. Here is an example:
using System;
public class Exercise
{
static int Main()
{
var drinkingUnderAge = true;
Console.WriteLine("Drinking Under Age: {0}", drinkingUnderAge);
return 0;
}
}This would produce:
Drinking Under Age: True
Press any key to continue . . .At any time and when you judge it necessary, you can change the value of the Boolean variable by assigning it a true or false value. Here is an example:
using System;
public class Exercise
{
static int Main()
{
var drinkingUnderAge = true;
Console.WriteLine("Drinking Under Age: {0}", drinkingUnderAge);
drinkingUnderAge = false;
Console.WriteLine("Drinking Under Age: {0}", drinkingUnderAge);
return 0;
}
}This would produce:
Drinking Under Age: True
Drinking Under Age: False
Press any key to continue . . .Retrieving the Value of a Boolean Variable#
As reviewed for the other data types, you can request the value of a Boolean variable from the user. In this case, the user must type either True (or true) or False (or false) and you can retrieve it using the Read() or the ReadLine() methods of the Console class. Here is an example:
using System;
public class Exercise
{
static int Main()
{
var drivingUnderAge = false;
Console.WriteLine("Were you driving under age?");
Console.Write("If Yes, enter True. Otherwise enter False: ");
drivingUnderAge = bool.Parse(Console.ReadLine());
Console.WriteLine("\nWas Driving Under Age: {0}\n", drivingUnderAge);
return 0;
}
}Here is an example of running the program:
Were you driving under age?
If Yes, enter True. Otherwise enter False: true
Was Driving Under Age: True
Press any key to continue . . .Creating a Boolean Field#
Like the other types of variables we used in previous lessons, a Boolean variable can be made a field of a class. You declare it like any other variable, using the bool keyword or the Boolean data type. Here is an example:
public class House
{
char typeOfHome;
int beds;
float baths;
byte stories;
bool hasCarGarage;
int yearBuilt;
double value;
}When initializing an object that has a Boolean variable as a member, simply assign true or false to the variable. In the same way, you can retrieve or check the value that a Boolean member variable is holding by simply accessing it. Here are examples:
using System;
public class House
{
public char typeOfHome;
public int beds;
public float baths;
public byte stories;
public bool hasCarGarage;
public int yearBuilt;
public double value;
}
public class Program
{
static int Main()
{
var Condominium = new
{
hasCarGarage = false,
yearBuilt = 2002,
baths = 1.5F,
stories = 18,
value = 155825,
beds = 2,
typeOfHome = 'C'
};
Console.WriteLine("=//= Altair Realtors =//=");
Console.WriteLine("=== Property Listing ===");
Console.WriteLine("Type of Home: {0}", Condominium.typeOfHome);
Console.WriteLine("Number of Bedrooms: {0}", Condominium.beds);
Console.WriteLine("Number of Bathrooms: {0}", Condominium.baths);
Console.WriteLine("Number of Stories: {0}", Condominium.stories);
Console.WriteLine("Year Built: {0}", Condominium.yearBuilt);
Console.WriteLine("Has Car Garage: {0}", Condominium.hasCarGarage);
Console.WriteLine("Monetary Value: {0}\n", Condominium.value);
return 0;
}
}This would produce:
=//= Altair Realtors =//=
=== Property Listing ===
Type of Home: C
Number of Bedrooms: 2
Number of Bathrooms: 1.5
Number of Stories: 18
Year Built: 2002
Has Car Garage: False
Monetary Value: 155825
Press any key to continue . . .Boolean Arguments#
Like parameters of the other types, you can pass an argument of type bool or Boolean to a method. Such an argument would be treated as holding a true or false value.
Logical Operators#
Introduction#
A program is a series of instructions that ask the computer (actually the compiler) to check some situations and to act accordingly. To check such situations, the computer spends a great deal of its time performing comparisons between values. A comparison is a Boolean operation that produces a true or a false result, depending on the values on which the comparison is performed. A comparison is performed between two values of the same type; for example, you can compare two numbers, two characters, or the names of two cities. On the other hand, a comparison between two disparate values doesn't bear any meaning. For example, it is difficult to compare a telephone number and somebody's age, or a music category and the distance between two points. Like the binary arithmetic operations, the comparison operations are performed on two values. Unlike arithmetic operations where results are varied, a comparison produces only one of two results. The result can be a logical true or a logical false. When a comparison is true, it has an integral value of 1 or positive; that is, a value greater than 0. If the comparison is not true, it is considered false and carries an integral value of 0. The C# language is equipped with various operators used to perform any type of comparison between similar values. The values could be numeric, strings, or objects (operations on objects are customized in a process referred to as Operator Overloading). There are primary assumptions you should make when writing statements used in conditions:
- Simplicity and Clarity: A statement should be clear enough and possibly simple but as complete as possible. When a statement becomes long, it can lead to being segmented in short parts, which deceives its clarity and may create other issues.
- Factual: The statement must be presented as fact and not as opinion. This means that you don't have to like the statement but the majority, including you, must agree that it is true or it is false. In fact, the statement doesn't have to be correct but it must be agreed upon to be true. Based on this, a statement such as "An hour contains 45 minutes" doesn't have to fit your way of thinking but it must be considered as true or as false. A statement such as "This job applicant is attractive" is an opinion and therefore must not be considered in a conditional statement.
- Circumstantial Truthfulness: At the time the statement is made, it must be considered as true or as false even if it can change at another time. For example, suppose that, in a certain year, a statement is formulated as "This year, the month of February has 28 days". Although allowed, you should refrain from regularly using circumstantial truthfulness, unless you have to.
- Inverse: A statement must be able to find its reverse. This means that, when a statement is made and decided upon to be true or false, an inverse statement must be found to make it false or true. For example, if you have a statement such as "This job applicant is 18 years old", you must be able to state that "This job applicant is not 18 years old" or "This job applicant is younger than 18".
In your programs, make sure you clearly formulate your statements. This would make your programs easy to read and troubleshoot when problems occur (not if, but when).
The Equality Operator ==#
To compare two variables for equality, C# uses the == operator. The formula used is:
value1 == Value2The equality operation is used to find out whether two variables (or one variable and a constant) hold the same value. From our syntax, the compiler would compare the value of Value1 with that of Value2. If Value1 and Value2 hold the same value, the comparison produces a true result. If they are different, the comparison renders false.
Most of the comparisons performed in C# will be applied to conditional statements. The result of a comparison can also be assigned to a variable. To store the result of a comparison, you should include the comparison operation between parentheses. Here is an example:
using System;
public class Exercise
{
static int Main()
{
var value1 = 15;
var value2 = 24;
Console.Write("Value 1 = ");
Console.WriteLine(value1);
Console.Write("Value 2 = ");
Console.WriteLine(value2);
Console.Write("Comparison of value1 == 15 produces ");
Console.WriteLine(value1 == 15);
return 0;
}
}This would produce:
Value 1 = 15
Value 2 = 24
Comparison of value1 == 15 produces TrueIt 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 to values. The operands on both sides of == can be variables, constants, or one can be a variable while the other is a constant. If you use one operator in place of the other, you would receive an error when you compile the program.
The Logical Not Operator !#
When a variable is declared and receives a value (this could be done through initialization or a change of value) in a program, it becomes alive. It can then participate in any necessary operation. The compiler keeps track of every variable that exists in the program being processed. When a variable is not being used or is not available for processing (in visual programming, it would be considered as disabled) to make a variable (temporarily) unusable, you can nullify its value. C# considers that a variable whose value is null is stern. To render a variable unavailable during the evolution of a program, apply the logical not operator which is !. Its syntax is:
!ValueThere are two main ways you can use the logical not operator. As we will learn when studying conditional statements, the most classic way of using the logical not operator is to check the state of a variable. To nullify a variable, you can write the exclamation point to its left. Here is an example:
using System;
public class Exercise
{
static int Main()
{
bool hasAirCondition = true;
bool doesIt;
Console.Write("hasAirCondition = ");
Console.WriteLine(hasAirCondition);
doesIt = !hasAirCondition;
Console.Write("doesIt = ");
Console.WriteLine(doesIt);
return 0;
}
}This would produce:
hasAirCondition = True
doesIt = FalseWhen a variable holds a value, it is "alive". To make it not available, you can "not" it. When a variable has been "notted", its logical value has changed. If the logical value was true, which is 1, it would be changed to false, which is 0. Therefore, you can inverse the logical value of a variable by "notting" or not "notting" it.
Less Than: <#
To find out whether one value is lower than another, use the < operator. Its syntax is:
Value1 < Value2Less Than of Equal To: <=#
The previous two operations can be combined to compare two values. This allows you to know if two values are the same or if the first is less than the second. The operator used is <= and its syntax is:
Value1 <= Value2The <= operation performs a comparison as any of the last two. If both Value1 and VBalue2 hold the same value, result is true or positive. If the left operand, in this case Value1, holds a value lower than the second operand, in this case Value2, the result is still true.
Greater Than or Equal To: >#
To find out if one value is greater than the other, you can use the > operator. Its formula is:
Value1 > Value2Both operands, in this case Value1 and Value2, can be variables or the left operand can be a variable while the right operand is a constant. If the value on the left of the > operator is greater than the value on the right side or a constant, the comparison produces a true or positive value . Otherwise, the comparison renders false or null:
The Greater Than or Equal Operator >=#
The greater than or the equality operators can be combined to produce an operator as follows: >=. This is the "greater than or equal to" operator. Its syntax is:
Value1 >= Value2A comparison is performed on both operands: Value1 and Value2. If the value of Value1 and that of Value2 are the same, the comparison produces a true or positive value. If the value of the left operand is greater than that of the right operand,, the comparison produces true or positive also. If the value of the left operand is strictly less than the value of the right operand, the comparison produces a false or null result:
Here is a summary table of the logical operators we have studied:
| Operator | Meaning | Example | Opposite |
|---|---|---|---|
| == | Equality to | a == b | != |
| != | Not equal to | 12 != 7 | == |
| < | Less than | 25 < 84 | >= |
| <= | Less than or equal to | Cab <= Tab | > |
| > | Greater than | 248 > 55 | <= |
| >= | Greater than or equal to | Val1 >= Val2 | < |
Home Copyright © 2010 C# Key Next

