Home

Controlling the Conditional Statements

 

Nesting a Conditional Statement

Consider the following program:

using System;

class Program
{
    static void Main()
    {
        int TypeOfHome;

        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");
	
        Console.WriteLine();
    }
}

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;

class Program
{
    static void Main()
    {
        int TypeOfHome;

        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());

            if ((TypeOfHome < 1) || (TypeOfHome > 3))
                Console.WriteLine("Invalid Choice: Please try againe");
        } 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");
	
        Console.WriteLine();
    }
}

Here is another example of running the program:

What Type of House Would you Like to Purchase?
1 - Single Family
2 - Town House
3 - Condominium
Your Choice? 0
Invalid Choice: Please try againe
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 . . .

Practical LearningPractical Learning: Nesting Conditions

  1. Access the OrderProcessing.cs file and change it as follows:
     
    using System;
    
    namespace FlowerShop3
    {
        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.Type = FlowerType.Roses;
                        break;
                    case 2:
                        FlowerOrder.Type = FlowerType.Lilies;
                        break;
                    case 3:
                        FlowerOrder.Type = FlowerType.Daisies;
                        break;
                    case 4:
                        FlowerOrder.Type = FlowerType.Carnations;
                        break;
                    case 5:
                        FlowerOrder.Type = FlowerType.LivePlant;
                        break;
                    default:
                        FlowerOrder.Type = 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.Color = FlowerColor.Red;
                        break;
                    case 2:
                        FlowerOrder.Color = FlowerColor.White;
                        break;
                    case 3:
                        FlowerOrder.Color = FlowerColor.Yellow;
                        break;
                    case 4:
                        FlowerOrder.Color = FlowerColor.Pink;
                        break;
                    case 5:
                        FlowerOrder.Color = FlowerColor.Yellow;
                        break;
                    case 6:
                        FlowerOrder.Color = FlowerColor.Blue;
                        break;
                    case 7:
                        FlowerOrder.Color = FlowerColor.Lavender;
                        break;
                    default:
                        FlowerOrder.Color = 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.Type);
                Console.WriteLine("Flower Color: {0}", FlowerOrder.Color);
                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("=======================");
            }
        }
    }
  2. 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
    
    =======================
    ==-=-=Flower Shop=-=-==
    -----------------------
    Flower Type:  Carnations
    Flower Color: Yellow
    Arrangement:  Basket
    Price:        $54.95
    Quantity:     1
    Total Price:  $54.95
    =======================
    
    Press any key to continue . . .
  3. 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;

class Program
{
    static void Main()
    {
        for (int Stories = 1; Stories <= 12; Stories++)
        {
            Console.WriteLine("Story {0}", Stories);
            if (Stories == 3)
                break;
        }
	
        Console.WriteLine();
    }
}

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;

class Program
{
    static void Main()
    {
        for (int Stories = 1; Stories <= 6; Stories++)
        {
            if (Stories == 3)
                continue;
            Console.WriteLine("Story {0}", Stories);
        }
	
        Console.WriteLine();
    }
}

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.

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;

class Program
{
    static void Main()
    {
        for (int 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");
    }
}

This would produce:

Story 1
Story 2
Story 3
Our homes have only up to 3 levels

Press any key to continue . . .

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 namespace System;

enum HouseType { Unknown, SingleFamily, TownHouse, Condominium };
HouseType GetHouseType();

int main()
{
	HouseType TypeOfHouse;

	TypeOfHouse = GetHouseType();
	
	switch(TypeOfHouse)
	{
	case SingleFamily:
		Console.WriteLine("\nType of Home: Single Family");
		break;
	case TownHouse:
		Console.WriteLine("\nType of Home: Town House");
		break;
	case Condominium:
		Console.WriteLine("\nType of Home: Condominium");
		break;
	case Unknown:
		Console.WriteLine("\nType of Home. Unknown");
		break;
	}

	Console.WriteLine();

	return 0;
}

HouseType GetHouseType()
{
	int type;

	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? ");
	type = int.Parse(Console.ReadLine());

	if( type == 1 )
		return SingleFamily;
	else if( type == 2 )
		return TownHouse;
	else if( type == 3 )
		return 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 value

To 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;

enum HouseType { Unknown, SingleFamily, TownHouse, Condominium };

class Program
{
    static HouseType GetHouseType()
    {
        int type;
        
        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? ");
        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;

        return HouseType.Unknown;
    }
    
    static void Main()
    {
        . . .
    }
}

Previous Copyright © 2006 FunctionX, Inc.