Topic F – If-Else Structures
Overview
This topic introduces the if-else control flow statement and demonstrates both simple and complex conditional expressions. This topic will also introduce how to nest program statements.
LOGs
General Programming Concepts and Terms
- Describe and draw a diagram of the If-Then-Else logical structure
- Identify the programming statement that corresponds to the If-Then-Else logical structure
- Translate If-Then-Else structures into code
- Describe what is meant by a “conditional expression”
- List the operator precedence for mixing logical, arithmetic, and relational operations
- List the relational operators
- List the logical operators
- Use relational, logical, and arithmetic operators to construct conditional expressions
- Demonstrate an understanding of operator precedence in conditional expressions
- Use statement blocks to allow nesting program statements into control structures
- Define the term “boundary condition” as it relates to if-else statements and testing
- Identify the correct way to compare or check the contents of strings in conditional expressions
- List and describe the commonly used properties and methods of the String class that would be used in if-else statements
Code Samples
The following examples are used to illustrate this topic.
- StockItem - This class represents an item that is part of an inventory. The item has an item name, a cost and a profit margin (which can be positive or negative). By using the profit margin, it can derive the price of the item. The class can also report if the item is priced at or below cost.
- Account - This class illustrates simple if structure in handling withdrawals; withdrawals are only made when the amount does not exceed the balance and the overdraft. It also identifies if the account is overdrawn.
- Person - This adaptation of the person class checks the age of the person to see if the person’s life stage is infant, toddler, preschooler, school age, or adult.
- Fraction - This class now ensures that any negative denominators have their negative sign “moved” to the numerator. It also recognizes whether a fraction is proper (numerator less than denominator) or not and provides a method to express the fraction as a mixed number string.
- Angle - This version of the Angle class includes an attribute to identify the type of the angle as either acute, right, obtuse, straight, reflex, full rotation, or undefined.
- ParkingCounter - This class represents a simple counter to monitor whether a parking lot is full or not; it tracks vehicles entering and leaving the parking lot and allows the counter to be reset when the lot is full or empty. This class illustrates increment and decrement operators and/or the assignment increment or assignment decrement operators.
- MemoryAddress - This class represents a single memory address in both its base 10 and hexadecimal value.
- Color - This class represents a color as three base-10 RGB values and as a single hexadecimal value.
- Base16 - This class represents an integer value as a base-16 hexadecimal number.
StockItem
This class represents an item that is part of an inventory. The item has an item name, a cost and a profit margin (which can be positive or negative). By using the profit margin, it can derive the price of the item. The class can also report if the item is priced at or below cost.
Problem Statement
Write the code for the StockItem class. The solution must meet the following requirements (new requirements are in bold):
- Should get and set the name, cost and profit margin of the stock item
- Should represent the profit margin as a percent; a value of 45 means 45%
- Should calculate the price of the item, to the nearest cent
- Use the rounding where values under a half-cent are rounded down and values greater than or equal to a half-cent are rounded up
- Should recognize when the stock item is priced at cost (that is, the profit margin is zero)
- Should recognize when the stock item is priced below cost (that is, the profit margin is negative)
Use the following class diagram when creating your solution.
1 public bool IsPricedAtCost
2 {
3 get
4 {
5 bool atCost = false;
6 if (ProfitMargin == 0)
7 atCost = true;
8 return atCost;
9 }
10 }
11
12 public bool IsPricedBelowCost
13 {
14 get
15 {
16 bool belowCost;
17 if (ProfitMargin < 0)
18 belowCost = true;
19 else
20 belowCost = false;
21 return belowCost;
22 }
23 }
Account
This class illustrates simple if structure in handling withdrawals; withdrawals are only made when the amount does not exceed the balance and the overdraft. It also identifies if the account is overdrawn.
Problem Statement
Write the code that will represent a simple bank account. The solution must meet the following requirements (new requirements are in bold):
- Should get the bank name, branch number, institution number, account number, balance, overdraft limit, and account type and allow the overdraft limit to be set
- Should support deposits
- Should only support withdrawals if the amount does not exceed the sum of the balance and the overdraft limit
- Should identify if the account is overdrawn
Use the following class diagram when creating your solution.
1 public double Withdraw(double amount)
2 {
3 if (amount <= Balance + OverdraftLimit)
4 Balance = Balance - amount;
5 else
6 amount = 0;
7 return amount;
8 }
9
10 public bool IsOverdrawn
11 {
12 get
13 {
14 bool overdrawn;
15 if (Balance < 0)
16 overdrawn = true;
17 else
18 overdrawn = false;
19 return overdrawn;
20 }
21 }
Person
This adaptation of the person class checks the age of the person to see if the person’s life stage is infant, toddler, preschooler, school age, or adult.
Problem Statement
Write the code that will represent a person with a first and last name and a date of birth. The solution must meet the following requirements (new requirements are in bold):
- Should get and set the first and last name
- Should get the birth date
- Should get the person’s approximate age (which is the age that the person will turn to in the current year)
- Should override ToString() to get the person’s full name (as first name then last name)
- Should get the life stage, based on the following table
| Age Range (Years) | Life Stage |
|---|---|
| 0 | Infant |
| < 3 | Toddler |
| < 5 | Preschooler |
| < 18 | School age |
| >= 18 | Adult |
Use the following class diagram when creating your solution.
1 public string LifeStage
2 {
3 get{
4 string stage;
5 if (Age == 0)
6 stage = "infant";
7 else if (Age < 3)
8 stage = "toddler";
9 else if (Age < 5)
10 stage = "preschooler";
11 else if (Age < 18)
12 stage = "school age";
13 else
14 stage = "adult";
15 return stage;
16 }
17 }
Fraction
This class now ensures that any negative denominators have their negative sign “moved” to the numerator. It also recognizes whether a fraction is proper (numerator less than denominator) or not and provides a method to express the fraction as a mixed number string.
Problem Statement
Write the code for the Fraction class. The solution must meet the following requirements (new requirements are in bold):
- Should get the string representation of the fraction, as “numerator/denominator”
- Should get the numeric value of the fraction (as a real number)
- Should get the reciprocal of the fraction
- Should get the numerator and denominator
- Should add another fraction to its existing value
- Should subtract another fraction from its existing value
- Should multiply its existing value by another fraction
- Should divide its existing value by another fraction
- Should affix the sign for negative fractions onto the numerator only
- Should identify if the fraction is a proper fraction
- Should express the fraction as a mixed number string
Use the following class diagram when creating your solution.
1 public Fraction(int numerator, int denominator)
2 {
3 Numerator = numerator;
4 Denominator = denominator;
5 FixSign();
6 }
7
8 private void FixSign()
9 {
10 if (Denominator < 0)
11 {
12 Denominator *= -1;
13 Numerator *= -1;
14 }
15 }
16
17 public bool IsProper
18 {
19 get
20 {
21 bool proper;
22 if (Numerator < Denominator)
23 proper = true;
24 else
25 proper = false;
26 return proper;
27 }
28 }
29
30 public override string ToString()
31 {
32 string stringValue = "";
33 if(IsProper)
34 stringValue += (Numerator / Denominator) + " and "
35 + (Numerator % Denominator) + "/" + Denominator;
36 else
37 stringValue += Numerator + "/" + Denominator;
38 return stringValue;
39 }
Angle
This version of the Angle class includes an attribute to identify the type of the angle as either acute, right, obtuse, straight, reflex, full rotation, or undefined.
Problem Statement
Write the code for the Angle class. The solution must meet the following requirements (new requirements are in bold):
- Should get and set the angle’s value (in degrees)
- Should calculate the equivalent angle in Radians and Grads, using the following formulas:
- Radians = Degrees * (π / 180)
- Grads = Radians * (200 / π)
- Should override the toString() method to return the angle in degrees, in the following format:
- degrees°
- The Unicode character for the degrees symbol (°) is ‘\u00B0’
- Should get the type of angle, based on the following table
| Angle Range | Angle Type |
|---|---|
| < = 0 or > 360 | Undefined |
| > 0 and < 90 | Acute |
| = 90 | Right |
| > 90 and < 180 | Obtuse |
| = 180 | Straight |
| > 180 and < 360 | Reflex |
| = 360 | Full Rotation |
Use the following class diagram when creating your solution.
1 public string AngleType
2 {
3 get
4 {
5 string angleType;
6 if (Degrees <= 0)
7 angleType = "undefined";
8 else if (Degrees < 90)
9 angleType = "acute";
10 else if (Degrees == 90)
11 angleType = "right";
12 else if (Degrees < 180)
13 angleType = "obtuse";
14 else if (Degrees == 180)
15 angleType = "straight";
16 else if (Degrees < 360)
17 angleType = "reflex";
18 else if (Degrees == 360)
19 angleType = "full rotation";
20 else
21 angleType = "undefined";
22 return angleType;
23 }
24 }
ParkingCounter
This class represents a simple counter to monitor whether a parking lot is full or not; it tracks vehicles entering and leaving the parking lot and allows the counter to be reset when the lot is full or empty. This class illustrates increment and decrement operators and/or the assignment increment or assignment decrement operators.
Problem Statement
Write the code that will monitor vehicles entering and leaving a parking lot. The solution must meet the following requirements (new requirements are in bold):
- Should track vehicles entering
- Should track vehicles leaving
-
Should track the peak occupancy of the parking lot
- The peak occupancy represents the highest number of cars in the parking lot at any one time
- Should get total parking spots
- Should get open (empty) spots
- Should reset lot as full (that is, fill the parking lot)
- Should reset lot as empty (that is, clear all the parking spots of vehicles)
Use the following class diagram when creating your solution.
1 public int PeakOccupancy { get; private set; }
2
3 public ParkingCounter(int parkingSpots)
4 {
5 this.ParkingSpots = parkingSpots;
6 this.OpenSpots = parkingSpots;
7 this.PeakOccupancy = 0;
8 }
9
10 public ParkingCounter(int parkingSpots, int numberOfCars)
11 {
12 this.ParkingSpots = parkingSpots;
13 this.OpenSpots = this.ParkingSpots - numberOfCars;
14 this.PeakOccupancy = numberOfCars;
15 }
16
17 public void enter()
18 {
19 OpenSpots--;
20 int numberOfCars = ParkingSpots - OpenSpots;
21 if (numberOfCars > PeakOccupancy)
22 PeakOccupancy = numberOfCars;
23 }
MemoryAddress
This class represents a single memory address in both its base 10 and hexadecimal value.
Base ten is the common number system that we use in every day life. Base ten uses the digits 0-9 and the concept of the position of a digit occupying some multiple of ten. Thus, for the number 129 there is a hundreds-position (102), a tens-position (101) and a ones-position (10^0).
1 129 base 10
2 ||\
3 |\ \_ 10^0 * 9 => 9
4 | \
5 \ \_ 10^2 * 2 => 20
6 \
7 \
8 \_ 10^3 * 1 => 100
9 ====
10 129
Converting a value from one base to another (such as base-10 to base-16) involves thinking about the digit positions of the target base. Base 16 uses the digits 0-9 along with the letters A through F for the range of hex values zero to fifteen. Each digit position in a base-16 number can hold a value of 0 to F. Thus, a digit in the ones position is worth 1 times the digit. A two-digit hex value would have the sixteens-position (161) and a ones-position (160). A three-digit hex value would add onto that a two-hundred-and-fifty-sixth-position (16^2). For example, to convert the number 679 base 10 to a base 16, you would follow these steps.
- Divide the original number by the two-hundred-and-fifty-sixth-position (162). Then use the remainder in calculating the next position (161).
\include{longdiv} \longdiv{679}{256}$ - Dividing the previous steps remainder (167) by 16 gives the result of 10, which is the hex-digit of
A.\include{longdiv} \longdiv{167}{16}$ - The remainder of that last step is the ones-position
- Thus, the base-10 value 679 is
2B9in base-16.
1 2B9 base 16
2 ||\
3 |\ \_ 16^0 * 9 => 9
4 | \
5 \ \_ 16^2 * 11 => 176
6 \
7 \
8 \_ 16^3 * 2 => 512
9 ====
10 679 base 10
The following class demonstrates a small memory address (up to four hexadecimal digits) as a short and a string representation of hexadecimal.
1 public class MemoryAddress
2 {
3 public short Base10Value { get; private set; }
4 public string HexValue
5 {
6 get
7 {
8 string hex = "0x";
9 // A short number in hexadecimal
10 // will be at most 4 digits
11 // FFFF
12 // ||||
13 // |||- 16^0 => 1
14 // ||-- 16^1 => 16
15 // |--- 16^2 => 256
16 // ---- 16^3 => 4096
17 int value = Base10Value;
18 int portion = value / 4096;
19 hex += ToHexDigit(portion);
20 value -= portion;
21 portion = value / 256;
22 hex += ToHexDigit(portion);
23 value -= portion;
24 portion = value / 16;
25 hex += ToHexDigit(portion);
26 portion = value % 16;
27 hex += ToHexDigit(portion);
28 return hex;
29 }
30 }
31
32 public MemoryAddress(short address)
33 {
34 Base10Value = address;
35 }
36
37 private static string ToHexDigit(int number)
38 {
39 string result;
40 if (number < 10)
41 result = number.ToString();
42 else if (number == 10)
43 result = "A";
44 else if (number == 11)
45 result = "B";
46 else if (number == 12)
47 result = "C";
48 else if (number == 13)
49 result = "D";
50 else if (number == 14)
51 result = "E";
52 else if (number == 15)
53 result = "F";
54 else // Should never happen...
55 result = "";
56
57 return result;
58 }
59 }
Color
This class represents a color as three base-10 RGB values and as a single hexadecimal value.
Problem Statement
Create a data type to represent a color as both base-10 RBG values and as a hexadecimal value.
1 public class Color
2 {
3 public byte Red { get; private set; }
4 public byte Blue { get; private set; }
5 public byte Green { get; private set; }
6
7 public string Hex
8 {
9 get
10 {
11 string converted = "#";
12 converted += ToHexDigit((byte)(Red / _Base16))
13 + ToHexDigit((byte)(Red % _Base16));
14 converted += ToHexDigit((byte)(Blue / _Base16))
15 + ToHexDigit((byte)(Blue % _Base16));
16 converted += ToHexDigit((byte)(Green / _Base16))
17 + ToHexDigit((byte)(Green % _Base16));
18 return converted;
19 }
20 }
21
22 private static byte _Base16 = (byte)16;
23 private static string ToHexDigit(byte number)
24 {
25 string result;
26 if (number < 10)
27 result = number.ToString();
28 else if (number == 10)
29 result = "A";
30 else if (number == 11)
31 result = "B";
32 else if (number == 12)
33 result = "C";
34 else if (number == 13)
35 result = "D";
36 else if (number == 14)
37 result = "E";
38 else if (number == 15)
39 result = "F";
40 else
41 result = "";
42
43 return result;
44 }
45
46 public Color(byte red, byte blue, byte green)
47 {
48 Red = red;
49 Blue = blue;
50 Green = green;
51 }
52 }
## Practice Excercises
- Rectangle – “All squares are rectangles, but not all rectangles are squares.” This class represents a simple rectangle with a height and width. From this information, the area, perimeter and diagonal can be obtained; it can also be determined if the rectangle is or is not square.
- HazardousMaterial – The HazardousMaterial class is a simple representation of the six main classes of hazardous materials (A through F). This class maps a classification code with a general description of the material’s classification:
- Class A – Compressed Gas
- Class B – Flammable and Combustible Material
- Class C – Oxidizing Material
- Class D – Poisonous and Infectious Material
- Class E – Corrosive Material
- Class F – Dangerously Reactive Material
- CurrencyCalculator – This exercise extends the previous CurrencyCalculator exercise by allowing the conversion from a foreign currency to US dollars.
- GravityCalculator – This exercise extends the previous GravityCalculator exercise by allowing the conversion to a weight on Earth from a weight on another planet in our solar system.
Rectangle
“All squares are rectangles, but not all rectangles are squares.” This class represents a simple rectangle with a height and width. From this information, the area, perimeter and diagonal can be obtained; it can also be determined if the rectangle is or is not square.
Problem Statement
Write the code for the Rectangle class. The solution must meet the following requirements:
- Should get and set the height and the width
- Should calculate the area, the perimeter and the diagonal
- The formula for the diagonal is √(〖width〗2 + 〖height〗2 )
- Should determine if the rectangle is a square
Use the following class diagram when creating your solution.
HazardousMaterial
The HazardousMaterial class is a simple representation of the six main classes of hazardous materials (A through F). This class maps a classification code with a general description of the material’s classification:
- Class A – Compressed Gas
- Class B – Flammable and Combustible Material
- Class C – Oxidizing Material
- Class D – Poisonous and Infectious Material
- Class E – Corrosive Material
- Class F – Dangerously Reactive Material
Problem Statement
Write the code for the HazardousMaterial class. The solution must meet the following requirements:
- Should return the class code as the classification
- Should get the description for the class, based on the following table
| Class Code | Description |
|---|---|
| A | Compressed Gas |
| B | Flammable and Combustible Material |
| C | Oxidizing Material |
| D | Poisonous and Infectious Material |
| E | Corrosive Material |
| F | Dangerously Reactive Material |
- Should override the ToString() method to get the full description and class code in the following format:
- “Class ClassCode - Description”
Use the following class diagram when creating your solution.
CurrencyCalculator
This exercise extends the previous CurrencyCalculator exercise by allowing the conversion from a foreign currency to US dollars.
Problem Statement
A currency exchange store at the international airport needs a program to convert from US dollars to four other currencies: Canadian dollar, Euro, Japanese Yen, and the Great Britain Pound. The store uses a set exchange rate for each currency as established at the start of the day. Write the code for a class called CurrencyCalculator to meet this need. The solution must meet the following requirements (new requirements are in bold):
- Should correctly convert US dollars to the
- British Pound (GBP)
- Canadian Dollar (CAD)
- Euro (EUR)
- Japanese Yen (JPY)
- Should convert an amount to US dollars from any of the supported currencies (GBP, CAD, JPY, and EUR)
- Should use the correct level of precision when making the exchange; each currency uses a different number of significant digits:
- CAD, GBP and EUR use two digits
- JPY uses three digits
To illustrate the possible exchange rates, please refer to the following images.
Use the following class diagram when creating your solution.
GravityCalculator
This exercise extends the previous GravityCalculator exercise by allowing the conversion to a weight on Earth from a weight on another planet in our solar system.
Problem Statement
Write the code needed to convert Earth weights to their equivalent for the other planets in our solar system. The solution must meet the following requirements (new requirements are in bold):
- Should convert a weight in Earth kilograms to their equivalent weight on
- Mercury
- Venus
- Mars
- Jupiter
- Saturn
- Uranus
- Neptune
- Should convert a weight from a specific planet back to the equivalent weight on Earth
Use the following class diagram when creating your solution.