Controlling the Conditional Statements
This is used to request one of the numbers 1, 2, or 3 from the user. Any number below 1 or above 3 is not accepted. Here is an example of running the program:
Nesting a Conditional Statement#
This example asks the user to choose one of the numbers 1, 2, or 3. Any value below 1 or above 3 is rejected, and the program shows a sample run afterward.
using System;
public class Exercise
{
public static int Main()
{
var typeOfHome = 0;
do
{
Console.WriteLine("What Type of House Would you Like to Purchase?");
Console.WriteLine("1 - Single Family");
Console.WriteLine("2 - Town House");
Console.WriteLine("3 - Condominium");
Console.Write("Your Choice? ");
typeOfHome = int.Parse(Console.ReadLine());
} while ((typeOfHome < 1) || (typeOfHome > 3));
if (typeOfHome == 1)
Console.WriteLine("\nType of Home: Single Family");
else if (typeOfHome == 2)
Console.WriteLine("\nType of Home: Town House");
else if (typeOfHome == 3)
Console.WriteLine("\nType of Home: Condominium");
return 0;
}
}This is used to request one of the numbers 1, 2, or 3 from the user. Any number below 1 or above 3 is not accepted. Here is an example of running the program:
What Type of House Would you Like to Purchase?
1 - Single Family
2 - Town House
3 - Condominium
Your Choice? 8
What Type of House Would you Like to Purchase?
1 - Single Family
2 - Town House
3 - Condominium
Your Choice? 6
What Type of House Would you Like to Purchase?
1 - Single Family
2 - Town House
3 - Condominium
Your Choice? 3
Type of Home: Condominium
Press any key to continue . . .If the user enters an invalid value, the question is simply being asked again. It would be professional to let the user know why the request came back even though what appears as a normal number was entered. To solve this and other types of problems, you can write one conditional statement inside of another. This is referred to as nesting. To create a conditional statement inside of another, simply proceed as we have done so far to create them. Here is an example:
using System;
public class Exercise
{
public static int Main()
{
var typeOfHome = 0;
do
{
Console.WriteLine("What Type of House Would you Like to Purchase?");
Console.WriteLine("1 - Single Family");
Console.WriteLine("2 - Townhouse");
Console.WriteLine("3 - Condominium");
Console.Write("Your Choice? ");
typeOfHome = int.Parse(Console.ReadLine());
if ((typeOfHome < 1) || (typeOfHome > 3))
Console.WriteLine("Invalid Choice: Please try again");
} while ((typeOfHome < 1) || (typeOfHome > 3));
if (typeOfHome == 1)
Console.WriteLine("\nType of Home: Single Family");
else if (typeOfHome == 2)
Console.WriteLine("\nType of Home: Townhouse");
else if (typeOfHome == 3)
Console.WriteLine("\nType of Home: Condominium");
return 0;
}
}If the user enters an invalid value, the question is asked again. It is more helpful to explain why the input was rejected even when it looks like a normal number. To handle this and similar situations, you can place one conditional statement inside another, which is called nesting.
What Type of House Would you Like to Purchase?
1 - Single Family
2 - Town House
3 - Condominium
Your Choice? 0
Invalid Choice: Please try again
What Type of House Would you Like to Purchase?
1 - Single Family
2 - Town House
3 - Condominium
Your Choice? 6
Invalid Choice: Please try againe
What Type of House Would you Like to Purchase?
1 - Single Family
2 - Town House
3 - Condominium
Your Choice? 2
Type of Home: Town House
Press any key to continue . . .Application: Nesting Conditions
- Access the OrderProcessing.cs file and change it as follows: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FlowerShop3 { public class OrderProcessing { public Flower flowerOrder; public int quantity; public OrderProcessing() { flowerOrder = new Flower(); } public decimal GetTotalPrice() { return quantity * flowerOrder.unitPrice; } public void GetFlowerType() { int choice = 0; do { 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: "); choice = int.Parse(Console.ReadLine()); if ((choice < 1) || (choice > 6)) Console.WriteLine("Invalid Value: Please enter a value between 1 and 6"); } while ((choice < 1) || (choice > 6)); switch (choice) { case 1: flowerOrder.typeOfFlower = FlowerType.Roses; break; case 2: flowerOrder.typeOfFlower = FlowerType.Lilies; break; case 3: flowerOrder.typeOfFlower = FlowerType.Daisies; break; case 4: flowerOrder.typeOfFlower = FlowerType.Carnations; break; case 5: flowerOrder.typeOfFlower = FlowerType.LivePlant; break; default: flowerOrder.typeOfFlower = FlowerType.Mixed; break; } } public void GetFlowerColor() { int choice = 0; do { 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: "); choice = int.Parse(Console.ReadLine()); if ((choice < 1) || (choice > 8)) Console.WriteLine("Invalid Value: Please enter a value between 1 and 8"); } while ((choice < 1) || (choice > 8)); switch (choice) { case 1: flowerOrder.majorColor = FlowerColor.Red; break; case 2: flowerOrder.majorColor = FlowerColor.White; break; case 3: flowerOrder.majorColor = FlowerColor.Yellow; break; case 4: flowerOrder.majorColor = FlowerColor.Pink; break; case 5: flowerOrder.majorColor = FlowerColor.Yellow; break; case 6: flowerOrder.majorColor = FlowerColor.Blue; break; case 7: flowerOrder.majorColor = FlowerColor.Lavender; break; default: flowerOrder.majorColor = FlowerColor.Mixed; break; } } public void GetFlowerArrangement() { int choice = 0; do { Console.WriteLine("Enter the Type of Arrangement"); Console.WriteLine("1. Bouquet"); Console.WriteLine("2. Vase"); Console.WriteLine("3. Basket"); Console.WriteLine("4. Mixed"); Console.Write("Your Choice: "); choice = int.Parse(Console.ReadLine()); if ((choice < 1) || (choice > 4)) Console.WriteLine("Invalid Value: Please enter a value between 1 and 4"); } while ((choice < 1) || (choice > 4)); switch (choice) { case 1: flowerOrder.arrangement = FlowerArrangement.Bouquet; break; case 2: flowerOrder.arrangement = FlowerArrangement.Vase; break; case 3: flowerOrder.arrangement = FlowerArrangement.Basket; break; default: flowerOrder.arrangement = FlowerArrangement.Any; break; } } public void ProcessOrder() { GetFlowerType(); GetFlowerColor(); GetFlowerArrangement(); Console.Write("Enter the Unit Price: "); flowerOrder.unitPrice = decimal.Parse(Console.ReadLine()); Console.Write("Enter Quantity: "); quantity = int.Parse(Console.ReadLine()); } public void ShowOrder() { Console.WriteLine("======================="); Console.WriteLine("==-=-=Flower Shop=-=-=="); Console.WriteLine("-----------------------"); Console.WriteLine("Flower Type: {0}", flowerOrder.typeOfFlower ); Console.WriteLine("Flower Color: {0}", flowerOrder.majorColor ); Console.WriteLine("Arrangement: {0}", flowerOrder.arrangement); Console.WriteLine("Price: {0:C}", flowerOrder.unitPrice); Console.WriteLine("Quantity: {0}", quantity); Console.WriteLine("Total Price: {0:C}", GetTotalPrice()); Console.WriteLine("======================="); } } }
- Execute the application and test it. Here is an example: Enter the Type of Flower Order 1. Roses 2. Lilies 3. Daisies 4. Carnations 5. Live Plant 6. Mixed Your Choice: 8 Invalid Value: Please enter a value between 1 and 6 Enter the Type of Flower Order 1. Roses 2. Lilies 3. Daisies 4. Carnations 5. Live Plant 6. Mixed Your Choice: 0 Invalid Value: Please enter a value between 1 and 6 Enter the Type of Flower Order 1. Roses 2. Lilies 3. Daisies 4. Carnations 5. Live Plant 6. Mixed Your Choice: 4 Enter the Color 1. Red 2. White 3. Yellow 4. Pink 5. Orange 6. Blue 7. Lavender 8. Mixed Your Choice: 9 Invalid Value: Please enter a value between 1 and 8 Enter the Color 1. Red 2. White 3. Yellow 4. Pink 5. Orange 6. Blue 7. Lavender 8. Mixed Your Choice: 3 Enter the Type of Arrangement 1. Bouquet 2. Vase 3. Basket 4. Mixed Your Choice: 9 Invalid Value: Please enter a value between 1 and 4 Enter the Type of Arrangement 1. Bouquet 2. Vase 3. Basket 4. Mixed Your Choice: 5 Invalid Value: Please enter a value between 1 and 4 Enter the Type of Arrangement 1. Bouquet 2. Vase 3. Basket 4. Mixed Your Choice: 3 Enter the Unit Price: 54.95 Enter Quantity: 1
- Press Enter ======================= ==-=-=Flower Shop=-=-== ----------------------- Flower Type: Carnations Flower Color: Yellow Arrangement: Basket Price: $54.95 Quantity: 1 Total Price: $54.95 =======================
- Close the DOS window
Breaking the Flow of a Conditional Statement#
The break statement is used to stop a loop for any reason or condition when necessary. The formula of the break statement is:
break;Although made of only one word, the break statement is a complete statement; therefore, it can (and should always) stay on its own line (this makes the program easy to read). The break statement applies to the most previous conditional statement to it; provided that previous statement is applicable. The break statement can be used in a while condition, in a do...while or a for loops to stop an ongoing action. Here is an example that is used to count the levels of a house from 1 to 12 but it is asked to stop at 3:
using System;
public class Exercise
{
public static int Main()
{
for (var stories = 1; stories <= 12; stories++)
{
Console.WriteLine("Story {0}", stories);
if (stories == 3)
break;
}
return 0;
}
}This would produce:
Story 1
Story 2
Story 3
Press any key to continue . . .Continuing a Conditional Statement#
The continue statement uses the following formula:
continue;When processing a loop, if the statement finds a false value, you can use the continue statement inside of a while, a do...while or a for conditional statements to ignore the subsequent statement or to jump from a false Boolean value to the subsequent valid value, unlike the break statement that would exit the loop. Like the break statement, the continue keyword applies to the most previous conditional statement and should stay on its own line. Here is an example when a program is supposed to count the levels of a house from 1 to 6:
using System;
public class Exercise
{
public static int Main()
{
for (var stories = 1; stories <= 6; stories++)
{
if (stories == 3)
continue;
Console.WriteLine("Story {0}", stories);
}
return 0;
}
}This would produce:
Story 1
Story 2
Story 4
Story 5
Story 6
Press any key to continue . . .Notice that, when the compiler gets to 3, it ignores it.
Changing a Value in the Loop#
Inside a loop, you may want to put a flag that would monitor the evolution of a tag so that, if the tag gets to a certain value, instead of skipping the looping by 1, you can make it jump to a valued range of your choice. To do this, in the loop, check the current value and if it gets to one you are looking for, change it. Here is an example where a loop is asked to count from 0 to 15:
using System;
public class Exercise
{
static int Main()
{
for (var story = 0; story < 15; story++)
{
if (story == 6)
story = 10;
Console.WriteLine("Elevator at: {0}", story);
}
return 0;
}
}This would produce:
Elevator at: 0
Elevator at: 1
Elevator at: 2
Elevator at: 3
Elevator at: 4
Elevator at: 5
Elevator at: 10
Elevator at: 11
Elevator at: 12
Elevator at: 13
Elevator at: 14
Press any key to continue . . .Notice that, when the loop reaches 6, it is asked to jump to number 10 instead.
Going to a Designated Label#
The goto statement allows a program execution to jump to another section of the function in which it is being used. In order to use the goto statement, insert a name on a particular section of your function so you can refer to that name. The name, also called a label, is made of one word and follows the rules we have learned about C++ names (the name can be anything), then followed by a colon. Here is an example where the program is supposed to count the levels of a 14 story building:
using System;
public class Exercise
{
public static int Main()
{
for (var stories = 1; stories <= 14; stories++)
{
if (stories == 4)
goto CountUpTo3;
Console.WriteLine("Story {0}", stories);
}
CountUpTo3:
Console.WriteLine("Our homes have only up to 3 levels\n");
return 0;
}
}This would produce:
Story 1
Story 2
Story 3
Our homes have only up to 3 levels
Press any key to continue . . .Issues on Methods and Conditional Statements#
while(true)#
For the different situations in which we used a while condition so far, we included a means of checking the condition. Instead, you can include juste the true Boolean constant in the parentheses of true. Here is an example:
using System;
public class Exercise
{
public static int Main()
{
while (true)
Console.WriteLine("C# Programming is fun!!!");
return 0;
}
}This type of statement is legal and would work fine. But it has no way of stopping because it is telling the compiler "As long as this is true, ...". The question is, what is "this"? As a result, the program would run for ever. Therefore, if you create a while(true) condition, in the body of the statement, you should provide a way for the compiler to stop, that is, a way for The condition to be false. This can be done by include an if condition. Here is an example:
using System;
public class Exercise
{
public static int Main()
{
int i = 0;
while (true)
{
if (i > 8)
break;
Console.WriteLine("C# Programming is fun!!!");
i++;
}
return 0;
}
}This time, the program is asking the compiler to keep displaying a sentence in the console screen by counting from 0 and up; but if the count reaches 8, to stop. The above program would produce:
C# Programming is fun!!!
C# Programming is fun!!!
C# Programming is fun!!!
C# Programming is fun!!!
C# Programming is fun!!!
C# Programming is fun!!!
C# Programming is fun!!!
C# Programming is fun!!!
C# Programming is fun!!!
Press any key to continue . . .In the above program, we used a break operator. You can use any other mechanism that can stop the looping, as long as at one time the condition would be false. Therefore, here is another way of stopping a while(true) loop:
using System;
public class Exercise
{
public static int Main()
{
int i = 0;
while (true)
{
if (i < 8)
Console.WriteLine("C# Programming is fun!!!");
else
return 0;
i++;
}
}
}This would produce the same result as previously. Instead of using while(true), you can first declare and initialize a Boolean variable, or you can use a Boolean variable whose value is already known. The value can come from a method or by other means. Application: Using while(true)
- To start a new application, on the main menu, click File -> New Project...
- In the middle list, click Empty Project
- Change the name to DepartmentStore8
- To create a new class, on the main menu, click Project -> Add Class...
- Change the Name to StoreItem and click Add
- Change the document as follows: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DepartmentStore8 { public class StoreItem { public int itemNumber; public string itemName; public string itemSize; public decimal unitPrice; public StoreItem() { itemNumber = 0; itemName = ""; itemSize = ""; unitPrice = 0.00M; } public StoreItem(int code, string name, string size, decimal price) { itemNumber = code; itemName = name; itemSize = size; unitPrice = price; } } }
- In the Solution Explorer, right-click DepartmentStore8 -> Add -> New Item...
- In the middle list, click Code File
- Change the Name to Inventory and press Enter
- Change the file as follows: using System; using DepartmentStore8; public class Inventory { static int Main() { StoreItem si = null; bool itemIsValid = true; Console.Title = "Department Store Inventory"; Console.WriteLine("Department Store Inventory"); while (itemIsValid) { si = new StoreItem(); Console.WriteLine("------------------------"); Console.Write("Enter Item #: "); si.itemNumber = int.Parse(Console.ReadLine()); if (si.itemNumber < 0) itemIsValid = false; else { Console.Write("Enter Item Name: "); si.itemName = Console.ReadLine(); Console.Write("Enter Item Size: "); si.itemSize = Console.ReadLine(); Console.Write("Enter Unit Price: "); si.unitPrice = decimal.Parse(Console.ReadLine()); Console.WriteLine("=-= Store Item =-="); Console.WriteLine("Item #: {0}", si.itemNumber); Console.WriteLine("Item Name: {0}", si.itemName); Console.WriteLine("Size: {0}", si.itemSize); Console.WriteLine("Unit Price: {0}", si.unitPrice); } } return 0; } }
- Execute the application to test it
- When requested, provide the data as follows: Item Number: 279475 Item Name: Wool Jersey Ruffle Dress Size: 8 Unit Price: 150 Item Number: 729070 Item Name: Mid-Weight Flat-Front Wool Trouser Pants Size: 36W - 30L Unit Price: 69.95 Item Number: 297004 Item Name: Ponte Pencil Skirt with Pleated Detail Size: 16 Unit Price: 80 Item Number: -1 Department Store Inventory ------------------------ Enter Item #: 279475 Enter Item Name: Wool Jersey Ruffle Dress Enter Item Size: 8 Enter Unit Price: 150 =-= Store Item =-= Item #: 279475 Item Name: Wool Jersey Ruffle Dress Size: 8 Unit Price: 150 ------------------------ Enter Item #: 729070 Enter Item Name: Mid-Weight Flat-Front Wool Trouser Pants Enter Item Size: 36W - 30L Enter Unit Price: 69.95 =-= Store Item =-= Item #: 729070 Item Name: Mid-Weight Flat-Front Wool Trouser Pants Size: 36W - 30L Unit Price: 69.95 ------------------------ Enter Item #: 297004 Enter Item Name: Ponte Pencil Skirt With Pleated Detail Enter Item Size: 16 Enter Unit Price: 80 =-= Store Item =-= Item #: 297004 Item Name: Ponte Pencil Skirt With Pleated Detail Size: 16 Unit Price: 80 ------------------------ Enter Item #: -1
- Close the DOS window and return to your programming environment
Returning From a Method#
So far, when defining a void method, we did not return a value. Here is an example:
using System;
public class Exercise
{
private void Show()
{
Console.WriteLine("C# Programming is fun!!!");
}
public static int Main()
{
Exercise exo = new Exercise();
exo.Show();
return 0;
}
}In reality a void method can perform a return, as long as it does not return a true value. This is used to signal to the compiler that it is time to get out of the method. To add such as flag, in the appropriate section of the void method, simply type return;. Here is an example:
using System;
public class Exercise
{
private void Show()
{
Console.WriteLine("C# Programming is fun!!!");
return;
}
public static int Main()
{
Exercise exo = new Exercise();
exo.Show();
return 0;
}
}In this case, the return; operation doesn't serve any true purpose. In the next section, we will see how it can be made useful when associated with a conditional statement.
Conditional Return#
Some functions are meant to return a value that is conditional of their processing. The fact that a function indicates the type of value it would return may not be clear at the time the function is closed but a function defined other than void must always return a value. You can write a conditional statement, such as if, inside of a function and return a value from that condition. Here is an example:
using System;
public class Program
{
enum HouseType { Unknown, SingleFamily, Townhouse, Condominium };
public static int Main()
{
var type = GetHouseType();
switch (type)
{
case HouseType.SingleFamily:
Console.WriteLine("\nType of Home: Single Family");
break;
case HouseType.Townhouse:
Console.WriteLine("\nType of Home: Townhouse");
break;
case HouseType.Condominium:
Console.WriteLine("\nType of Home: Condominium");
break;
case HouseType.Unknown:
Console.WriteLine("\nType of Home. Unknown");
break;
}
return 0;
}
private static HouseType GetHouseType()
{
var type = 0;
Console.WriteLine("What Type of House Would you Like to Purchase?");
Console.WriteLine("1 - Single Family");
Console.WriteLine("2 - Townhouse");
Console.WriteLine("3 - Condominium");
Console.Write("Your Choice? ");
type = int.Parse(Console.ReadLine());
if (type == 1)
return HouseType.SingleFamily;
else if (type == 2)
return HouseType.Townhouse;
else if (type == 3)
return HouseType.Condominium;
}
}This GetHouseType() method indicates when one of three values is returned. In reality, this method could get a value other than the three that are considered. If the user enters such a value, the current version of the method would not know what to do. For this reason, the program will not compile. In Microsoft Visual C#, you would receive the following error:
'Program.GetHouseType()': not all code paths return a valueTo solve this problem, you must provide a statement that would include any value other than those considered. You can do this by writing a final return that has its own value. Here is an example:
using System;
public class Program
{
enum HouseType { Unknown, SingleFamily, Townhouse, Condominium };
public static int Main()
{
var type = GetHouseType();
switch (type)
{
case HouseType.SingleFamily:
Console.WriteLine("\nType of Home: Single Family");
break;
case HouseType.Townhouse:
Console.WriteLine("\nType of Home: Townhouse");
break;
case HouseType.Condominium:
Console.WriteLine("\nType of Home: Condominium");
break;
case HouseType.Unknown:
Console.WriteLine("\nType of Home. Unknown");
break;
}
return 0;
}
private static HouseType GetHouseType()
{
var type = 0;
Console.WriteLine("What Type of House Would you Like to Purchase?");
Console.WriteLine("1 - Single Family");
Console.WriteLine("2 - Townhouse");
Console.WriteLine("3 - Condominium");
Console.Write("Your Choice? ");
type = int.Parse(Console.ReadLine());
if (type == 1)
return HouseType.SingleFamily;
else if (type == 2)
return HouseType.Townhouse;
else if (type == 3)
return HouseType.Condominium;
else
return HouseType.Unknown;
}
}Home Copyright © 2010 C# Key

