Home

Conditional Statements

 

Conditions

 

Introduction

A conditional expression is an expression that produces a true or false result. You can then use that result as you see fit. To create the expression, you use the Boolean operators we studied in the previous lesson. In the previous lesson, we saw only how to perform the operations and how to get the results, not how to use them. To use the result of a Boolean operation, the C++ programming language provides some specific conditional operators.

Practical LearningPractical Learning: Introducing Conditional Expressions

  1. Start Microsoft Visual C++ 2005
  2. On the main menu, click File -> New -> Project...
  3. On the left side, make sure that Visual C++ is selected. In the Templates list, click CLR Empty Project
  4. In the Name box, replace the string with ElectroStore6 and click OK
  5. On the main menu, click Project -> Add Class...
  6. In the Categories lists, expand Visual C++ and click C++.
    In the Templates list, make sure C++ Class is selected and click Add
  7. Set the Name of the class to CStoreItem and click Finish
  8. Complete the StoreItem.h header file as follows:
     
    #pragma once
    using namespace System;
    
    public enum class ItemsCategories
    {
        Unknown,
        CablesAndConnectors,
        CellPhonesAndAccessories,
        Headphones,
        DigitalCameras,
        PDAsAndAccessories,
        TelephonesAndAccessories,
        TVsAndVideos,
        SurgeProtectors,
        Instructional
    };
    
    namespace ElectronicsStore
    {
        public ref class CStoreItem
        {
        public:
            // An item whose characteristics are not (yet) defined
            CStoreItem(void);
            // An item that is known by its make, model, and unit price
            CStoreItem(long itmNbr, String ^ make,
    		   String ^ model, double unitPrice);
            // An item that is known by its name and unit price
            CStoreItem(long itmNbr, String ^ name, double unitPrice);
            // An item completely defined
            CStoreItem(long itmNbr, ItemsCategories category,
    	           String ^ make, String ^ model, double unitPrice);
            ~CStoreItem();
    
        private:
            long            nbr;
            ItemsCategories cat;
            String        ^ mk;
            String        ^ mdl;
            String        ^ nm;
            double          price;
    
        public:
            property long ItemNumber
            {
                long get() { return nbr; }
                void set(long n) { this->nbr = n; }
            }
    
            property ItemsCategories Category
            {
                ItemsCategories get() { return cat; }
    	        void set(ItemsCategories c) { this->cat = c; }
            }
    
            property String ^ Make
            {
    	    String ^ get() { return mk; }
    	    void set(String ^ m) { this->mk = m; }
            }
    
            property String ^ Model
            {
    	    String ^ get() { return mdl; }
    	    void set(String ^ m) { this->mdl = m; }
            }
    
            property String ^ Name
            {
                String ^ get() { return nm; }
    	    void set(String ^ n) { this->nm = n; }
            }
    
            property double UnitPrice
            {
    	    double get() { return price; }
    	    void set(double p) { this->price = p; }
            }
        };
    }
  9. Access the StoreItem.cpp source file and change it as follows:
     
    #include "StoreItem.h"
    
    namespace ElectronicsStore
    {
        CStoreItem::CStoreItem(void)
        {
            nbr      = 0;
    	cat      = ItemsCategories::Unknown;
            mk       = L"Unknown";
            mdl      = L"Unspecified";
            nm       = L"N/A";
            price    = 0.00;
        }
    
        CStoreItem::CStoreItem(long itmNbr, String ^ make,
    			   String ^ model, double unitPrice)
        {
            nbr      = itmNbr;
            cat      = ItemsCategories::Unknown;
            mk       = make;
            mdl      = model;
            nm       = L"N/A";
            price    = unitPrice;
        }
        
        CStoreItem::CStoreItem(long itmNbr, String ^ name,
    				double unitPrice)
        {
            nbr      = itmNbr;
            cat      = ItemsCategories::Unknown;
            mk       = L"Unknown";
            mdl      = L"Unspecified";
            nm       = name;
            price    = unitPrice;
        }
        
        CStoreItem::CStoreItem(long itmNbr, ItemsCategories category,
    			   String ^ make, String ^ model,
    			   double unitPrice)
        {
            nbr      = itmNbr;
            cat      = category;
            mk       = make;
            mdl      = model;
            price    = unitPrice;
        }
    
        CStoreItem::~CStoreItem()
        {
        }
    }
  10. To create one more source file, on the main menu, click Project -> Add New Item...
  11. In the Templates list, make sure C++ File (.cpp) is selected.
    Set the Name to Exercise and click Add
  12. Complete the file as follows:
     
    #include "StoreItem.h"
    
    using namespace System;
    
    int main()
    {
        String ^ strTitle = L"=-= Nearson Electonics =-=\n"
    		        L"******* Store Items ******";
    
        Console::WriteLine();
        return 0;
    }
  13. Execute the application to make sure it can compile
  14. Close the DOS window

if a Condition is True

Consider the following program:

using namespace System;

int main()
{
    __wchar_t TypeOfHome;

    Console::WriteLine(L"What Type of House Would you Like to Purchase?");
    Console::WriteLine(L"S - Single Family");
    Console::WriteLine(L"T - Town House");
    Console::WriteLine(L"C - Condominium");
    Console::Write(L"Your Choice? ");
    TypeOfHome = __wchar_t::Parse(Console::ReadLine());

    Console::WriteLine(L"\nType of Home: {0}", TypeOfHome);
    Console::WriteLine();

    return 0;
}

Here is an example of running the program:

What Type of House Would you Like to Purchase?
S - Single Family
T - Town House
C - Condominium
Your Choice? S

Type of Home: S

Press any key to continue . . .

To check if an expression is true and use its Boolean result, you can use the if operator. Its formula is:

if(Condition) Statement;

The Condition can be the type of Boolean operation we studied in the previous lesson. That is, it can have the following formula:

Operand1 BooleanOperator Operand2

If the Condition produces a true result, then the compiler executes the Statement. If the statement to execute is short, you can write it on the same line with the condition that is being checked. Here is an example:

using namespace System;

int main()
{
    __wchar_t TypeOfHome;

    Console::WriteLine(L"What Type of House Would you Like to Purchase?");
    Console::WriteLine(L"S - Single Family");
    Console::WriteLine(L"T - Town House");
    Console::WriteLine(L"C - Condominium");
    Console::Write(L"Your Choice? ");
    TypeOfHome = __wchar_t::Parse(Console::ReadLine());

    Console::Write(L"");
    if(TypeOfHome == L'S') Console::WriteLine(L"\nType of Home: Single Family");

    Console::WriteLine();
    return 0;
}

Here is an example of running the program:

What Type of House Would you Like to Purchase?
S - Single Family
T - Town House
C - Condominium
Your Choice? S

Type of Home: Single Family

Press any key to continue . . .

If the Statement is too long, you can write it on a different line than the if condition. Here is an example:

using namespace System;

int main()
{
    __wchar_t TypeOfHome;

    Console::WriteLine(L"What Type of House Would you Like to Purchase?");
    Console::WriteLine(L"S - Single Family");
    Console::WriteLine(L"T - Town House");
    Console::WriteLine(L"C - Condominium");
    Console::Write(L"Your Choice? ");
    TypeOfHome = __wchar_t::Parse(Console::ReadLine());

    if(TypeOfHome == L'S')
	Console::WriteLine(L"\nType of Home: Single Family");

    Console::WriteLine();
    return 0;
}

You can also write the Statement on its own line if the statement is short enough to fit on the same line with the Condition.

Although the (simple) if statement is used to check one condition, it can lead to executing multiple dependent statements. If that is the case, enclose the group of statements between an opening curly bracket “{“ and a closing curly bracket “}”. Here is an example:

using namespace System;

int main()
{
	__wchar_t TypeOfHome;

	Console::WriteLine(L"What Type of House Would you Like to Purchase?");
	Console::WriteLine(L"S - Single Family");
	Console::WriteLine(L"T - Town House");
	Console::WriteLine(L"C - Condominium");
	Console::Write(L"Your Choice? ");
	TypeOfHome = __wchar_t::Parse(Console::ReadLine());

	if(TypeOfHome == L'S')
	{
		Console::Write(L"\nType of Home: ");
		Console::WriteLine(L"Single Family");
	}

	Console::WriteLine();

	return 0;
}

If you omit the brackets, only the statement that immediately follows the condition would be executed. Just as you can write one if condition, you can write more than one. Here are examples:

using namespace System;

int main()
{
	__wchar_t TypeOfHome;

	Console::WriteLine(L"What Type of House Would you Like to Purchase?");
	Console::WriteLine(L"S - Single Family");
	Console::WriteLine(L"T - Town House");
	Console::WriteLine(L"C - Condominium");
	Console::Write(L"Your Choice? ");
	TypeOfHome = __wchar_t::Parse(Console::ReadLine());

	if(TypeOfHome == L'S')
		Console::WriteLine(L"\nType of Home: Single Family");
	if(TypeOfHome == L'T')
		Console::WriteLine(L"\nType of Home: Town House");
	if(TypeOfHome == L'C')
		Console::WriteLine(L"\nType of Home: Condominium");

	Console::WriteLine();

	return 0;
}

Here is an example of running the program:

What Type of House Would you Like to Purchase?
S - Single Family
T - Town House
C - Condominium
Your Choice? C

Type of Home: Condominium

Press any key to continue . . .

Practical LearningPractical Learning: Using the Simple if Condition

  1. To use the if condition, change the contents of the Exercise.cpp source file as follows:
     
    #include "StoreItem.h"
    
    using namespace System;
    using namespace ElectronicsStore;
    
    CStoreItem ^ CreateStoreItem();
    static void DescribeStoreItem(CStoreItem ^ %);
    
    int main()
    {
        String ^ strTitle = L"=-= Nearson Electonics =-=\n"
    		        L"******* Store Items ******";
    
        CStoreItem ^ saleItem = CreateStoreItem();
    
        Console::WriteLine(L"");
        DescribeStoreItem(saleItem, 0);
    
        Console::WriteLine();
        return 0;
    }
    
    CStoreItem ^ CreateStoreItem()
    {
        CStoreItem ^ sItem = gcnew CStoreItem;
        int      category;
    
        Console::WriteLine(L"To create a store item, enter its information");
        Console::Write(L"Item Number: ");
        sItem->ItemNumber   = long::Parse(Console::ReadLine());
        Console::WriteLine(L"Category");
        Console::WriteLine(L"1.  Unknown/Miscellaneous");
        Console::WriteLine(L"2.  Cables and Connectors");
        Console::WriteLine(L"3.  Cell Phones and Accessories");
        Console::WriteLine(L"4.  Headphones");
        Console::WriteLine(L"5.  Digital Cameras");
        Console::WriteLine(L"6.  PDAs and Accessories");
        Console::WriteLine(L"7.  Telephones and Accessories");
        Console::WriteLine(L"8.  TVs and Videos - Plasma / LCD");
        Console::WriteLine(L"9.  Surge Protector");
        Console::WriteLine(L"10. Instructional and Tutorials (VHS & DVD)TVs and Videos");
        Console::Write(L"Your Choice? ");
        category = int::Parse(Console::ReadLine());
    
        if( category == 1 )
    	sItem->Category = ItemsCategories::Unknown;
        if( category == 2 )
    	sItem->Category = ItemsCategories::CablesAndConnectors;
        if( category == 3 )
    	sItem->Category = ItemsCategories::CellPhonesAndAccessories;
        if( category == 4 )
    	sItem->Category = ItemsCategories::Headphones;
        if( category == 5 )
    	sItem->Category = ItemsCategories::DigitalCameras;
        if( category == 6 )
    	sItem->Category = ItemsCategories::PDAsAndAccessories;
        if( category == 7 )
    	sItem->Category = ItemsCategories::TelephonesAndAccessories;
        if( category == 8 )
    	sItem->Category = ItemsCategories::TVsAndVideos;
        if( category == 9 )
    	sItem->Category = ItemsCategories::SurgeProtectors;
        if( category == 10 )
    	sItem->Category = ItemsCategories::Instructional;
    
        Console::Write(L"Make         ");
        sItem->Make = Console::ReadLine();
        Console::Write(L"Model:       ");
        sItem->Model = Console::ReadLine();
        Console::Write(L"Unit Price:  ");
        sItem->UnitPrice = double::Parse(Console::ReadLine());
    
        return sItem;
    }
    
    void DescribeStoreItem(CStoreItem ^ %item)
    {
        Console::WriteLine(L"Store Item Description");
        Console::WriteLine(L"Item Number:   {0}", item->ItemNumber);
        Console::WriteLine(L"Category:      {0}", item->Category);
        Console::WriteLine(L"Make           {0}", item->Make);
        Console::WriteLine(L"Model:         {0}", item->Model);
        Console::WriteLine(L"Unit Price:    {0:C}", item->UnitPrice);
    }
  2. Execute the application to see the result. Here is an example:
     
    To create a store item, enter its information
    Item Number: 237875
    Category
    1.  Unknown/Miscellaneous
    2.  Cables and Connectors
    3.  Cell Phones and Accessories
    4.  Headphones
    5.  Digital Cameras
    6.  PDAs and Accessories
    7.  Telephones and Accessories
    8.  TVs and Videos - Plasma / LCD
    9.  Surge Protector
    10. Instructional and Tutorials (VHS & DVD)TVs and Videos
    Your Choice? 4
    Make         Tritton
    Model:       AX360
    Unit Price:  145.85
    
    Store Item Description
    Item Number:   237875
    Category:      Headphones
    Make           Tritton
    Model:         AX360
    Unit Price:    $145.85
    
    Press any key to continue . . .
  3. Close the DOS window

if…else

If you use an if condition to perform an operation and if the result is true, we saw that you could execute the statement. As we saw in the previous section, any other result would be ignored. To address an alternative to an if condition, you can use the else condition. The formula to follow is:

if(Condition)
    Statement1;
else
    Statement2;

Once again, the Condition can be a Boolean operation like those we studied in the previous lesson. If the Condition is true, then the compiler would execute Statement1. If the Condition is false, then the compiler would execute Statement2. Here is an example:

using namespace System;

int main()
{
	Byte Stories;

	Console::Write(L"What's the maximum number of levels you want? ");
	Stories = Byte::Parse(Console::ReadLine());

	if(Stories == 1 )
		Console::WriteLine(L"\nMaximum Levels: Single Level");
	else
		Console::WriteLine(L"\nMaximum Levels: Any Number");

	Console::WriteLine();

	return 0;
}

Here is an example of running the program:

What's the maximum number of levels you want? 3

Maximum Levels: Any Number

Press any key to continue . . .

Here is another example of running the program:

What's the maximum number of levels you want? 1

Maximum Levels: Single Level

Press any key to continue . . .

Practical LearningPractical Learning: Using the if...else Condition

  1. Access the StoreItem.h header file
  2. To use the if...else condition, change the UnitPrice property as follows:
     
    #pragma once
    using namespace System;
    
    . . .
    
    namespace ElectronicsStore
    {
        public ref class CStoreItem
        {
        public:
            . . .
    
        private:
            long            nbr;
            ItemsCategories cat;
            String        ^ mk;
            String        ^ mdl;
            String        ^ nm;
            double          price;
    
        public:
            . . .
    
            property double UnitPrice
            {
    	    double get() { return price; }
    	    void set(double p)
                {
                    if( p <= 0 )
                        this->price = 0.00;
                    else
                        this->price = p;
                }
            }
        };
    }
  3. Access the Exercise.cpp file and change it as follows:
     
    #include "StoreItem.h"
    
    using namespace System;
    using namespace ElectronicsStore;
    
    CStoreItem ^ CreateStoreItem();
    static void DescribeStoreItem(CStoreItem ^ %);
    static void DescribeStoreItem(CStoreItem ^ %, const int);
    
    int main()
    {
        String ^ strTitle = L"=-= Nearson Electonics =-=\n"
    		        L"******* Store Items ******";
    
        CStoreItem ^ saleItem = CreateStoreItem();
    
        Console::WriteLine(L"");
    
        if( saleItem->Category == ItemsCategories::Unknown )
            DescribeStoreItem(saleItem, 0);
        else
            DescribeStoreItem(saleItem);
    
        Console::WriteLine();
        return 0;
    }
    
    CStoreItem ^ CreateStoreItem()
    {
        CStoreItem ^ sItem = gcnew CStoreItem;
        int      category;
    
        Console::WriteLine(L"To create a store item, enter its information");
        Console::Write(L"Item Number: ");
        sItem->ItemNumber   = long::Parse(Console::ReadLine());
        Console::WriteLine(L"Category");
        Console::WriteLine(L"1.  Unknown/Miscellaneous");
        Console::WriteLine(L"2.  Cables and Connectors");
        Console::WriteLine(L"3.  Cell Phones and Accessories");
        Console::WriteLine(L"4.  Headphones");
        Console::WriteLine(L"5.  Digital Cameras");
        Console::WriteLine(L"6.  PDAs and Accessories");
        Console::WriteLine(L"7.  Telephones and Accessories");
        Console::WriteLine(L"8.  TVs and Videos - Plasma / LCD");
        Console::WriteLine(L"9.  Surge Protector");
        Console::WriteLine(L"10. Instructional and Tutorials (VHS & DVD)TVs and Videos");
        Console::Write(L"Your Choice? ");
        category = int::Parse(Console::ReadLine());
    
        // If the user specifies that the type is not known
        // then we need only the name/description of the item
        if( category == 1 )
        {
            sItem->Category = ItemsCategories::Unknown;
            Console::Write(L"Enter the item name or description: ");
            sItem->Name = Console::ReadLine();
        }
        else
        {
            if( category == 2 )
                sItem->Category = ItemsCategories::CablesAndConnectors;
            if( category == 3 )
                sItem->Category = ItemsCategories::CellPhonesAndAccessories;
            if( category == 4 )
                sItem->Category = ItemsCategories::Headphones;
            if( category == 5 )
    	    sItem->Category = ItemsCategories::DigitalCameras;
            if( category == 6 )
                sItem->Category = ItemsCategories::PDAsAndAccessories;
            if( category == 7 )
    	    sItem->Category = ItemsCategories::TelephonesAndAccessories;
            if( category == 8 )
    	    sItem->Category = ItemsCategories::TVsAndVideos;
            if( category == 9 )
    	    sItem->Category = ItemsCategories::SurgeProtectors;
            if( category == 10 )
                sItem->Category = ItemsCategories::Instructional;
    
    	// If the user selected a category other than Unknown
    	// then ask the make and model of the item
            Console::Write(L"Make         ");
            sItem->Make = Console::ReadLine();
            Console::Write(L"Model:       ");
            sItem->Model = Console::ReadLine();
        }
    
        Console::Write(L"Unit Price:  ");
        sItem->UnitPrice = double::Parse(Console::ReadLine());
    
        return sItem;
    }
    // This function is used when an item is specified by its make and model
    void DescribeStoreItem(CStoreItem ^ %item)
    {
        Console::WriteLine(L"Store Item Description");
        Console::WriteLine(L"Item Number:   {0}", item->ItemNumber);
        Console::WriteLine(L"Category:      {0}", item->Category);
        Console::WriteLine(L"Make           {0}", item->Make);
        Console::WriteLine(L"Model:         {0}", item->Model);
        Console::WriteLine(L"Unit Price:    {0:C}", item->UnitPrice);
    }
    
    // This function is used when an item is specified by its name
    void DescribeStoreItem(CStoreItem ^ %item, const int)
    {
        Console::WriteLine(L"Store Item Description");
        Console::WriteLine(L"Item Number:   {0}", item->ItemNumber);
        Console::WriteLine(L"Category:      Miscellaneous/Accessories");
        Console::WriteLine(L"Name:          {0}", item->Name);
        Console::WriteLine(L"Unit Price:    {0:C}", item->UnitPrice);
    }
  4. Execute the application to test it. After enter the item number, select a category other than 1 and continue with the rest. Here is an example:
     
    To create a store item, enter its information
    Item Number: 204006
    Category
    1.  Unknown/Miscellaneous
    2.  Cables and Connectors
    3.  Cell Phones and Accessories
    4.  Headphones
    5.  Digital Cameras
    6.  PDAs and Accessories
    7.  Telephones and Accessories
    8.  TVs and Videos - Plasma / LCD
    9.  Surge Protector
    10. Instructional and Tutorials (VHS & DVD)TVs and Videos
    Your Choice? 5
    Make         Kodak
    Model:       Easyshare CD33
    Unit Price:  69.95
    
    Store Item Description
    Item Number:   204006
    Category:      DigitalCameras
    Make           Kodak
    Model:         Easyshare CD33
    Unit Price:    $69.95
    
    Press any key to continue . . .
  5. Close the DOS window
  6. Execute the application again. After enter the item number, enter 1 for the category and continue with the rest. Here is an example:
     
    To create a store item, enter its information
    Item Number: 268240
    Category
    1.  Unknown/Miscellaneous
    2.  Cables and Connectors
    3.  Cell Phones and Accessories
    4.  Headphones
    5.  Digital Cameras
    6.  PDAs and Accessories
    7.  Telephones and Accessories
    8.  TVs and Videos - Plasma / LCD
    9.  Surge Protector
    10. Instructional and Tutorials (VHS & DVD)TVs and Videos
    Your Choice? 1
    Enter the item name or description: VoIP Startup Kit
    Unit Price:  88.85
    
    Store Item Description
    Item Number:   268240
    Category:      Miscellaneous/Accessories
    Name:          VoIP Startup Kit
    Unit Price:    $88.85
    
    Press any key to continue . . .
  7. Close the Dos window

The Ternary Operator (?:)

The ternary operator behaves like a simple if…else statement. Its formula is:

Condition ? Statement1 : Statement2;

Here is an example:

using namespace System;

int main()
{
    Byte Stories;

    Console::Write(L"What's the maximum number of levels you want? ");
    Stories = Byte::Parse(Console::ReadLine());

    (Stories == 1) ? 
	Console::WriteLine(L"\nSingle Level") : 
	Console::WriteLine(L"\nAny Number of Levels");

    Console::WriteLine();
    return 0;
}

In Lesson 4, we saw different techniques of creating a constant. We saw that a constant must be initialized when it is created. In some cases, the constant you want to apply to a variable may depend on other variables. You cannot just use a conditional statement to control the value of a constant. The ternary operator provides an alternate solution to this problem. To use it, create a ?: operation and assign it to the constant variable. Here is an example:

using namespace System;

int main()
{
    int x = 258;
    const double y = (x <= 255 ? 1550.95 : 450.75);

    Console::WriteLine(L"x = {0}", x);
    Console::WriteLine(L"y = {0:F}", y);

    Console::WriteLine();
    return 0;
}

This would produce:

x = 258
y = 450.75

Press any key to continue . . .

Practical LearningPractical Learning: Using the Ternary Operator

  1. On the main menu, click File -> New -> Project...
  2. On the left side, make sure that Visual C++ is selected. In the Templates list, click CLR Empty Project
  3. In the Name box, replace the string with FlowerShop3 and click OK
  4. On the main menu, click Project -> Add Class...
  5. In the Categories lists, expand Visual C++ and click C++.
    In the Templates list, make sure C++ Class is selected and click Add
  6. Set the Name of the class to CFlower and click Finish
  7. Complete the Flower.h header file as follows:
     
    #pragma once
    
    public enum class FlowerType
    {
        Roses = 1,
        Lilies,
        Daisies,
        Carnations,
        LivePlant,
        Mixed
    };
    
    public enum class FlowerColor
    {
        Red = 1,
        White,
        Yellow,
        Pink,
        Orange,
        Blue,
        Lavender,
        Mixed
    };
    
    public enum class FlowerArrangement
    {
        Bouquet = 1,
        Vase,
        Basket,
        Mixed
    };
    
    public ref class CFlower
    {
    private:
        int _tp;
        int _clr;
        int _arg;
        bool _mx;
        double   _price;
    
    public:
        property int Type
        {
            int get() { return _tp; }
            void set(int tp)
            {
    	    _tp = (tp <= 0 ? 0 : tp);
            }
        }
    
        property int Color
        {
            int get() { return _clr; }
            void set(int clr)
            {
    	    _clr = (clr <= 0 ? 0 : clr);
            }
        }
    
        property int Arrangement
        {
            int get() { return _arg; }
            void set(int arg)
            {
    	    _arg = (arg <= 0 ? 0 : arg);
            }
        }
    
        property bool Mixed
        {
    	bool get() { return _mx; }
    	void set(bool mx) { _mx = mx; }
        }
    
        property double UnitPrice
        {
            double get() { return _price; }
            void set(double price)
            {
    	    _price = (price <= 0.00 ? 0.00 : price);
            }
        }
    
    public:
        CFlower(void);
        CFlower(int type, int color,
                int argn, bool mx, double price);
        ~CFlower();
    };
  8. Complete the Flower.cpp source file as follows:
     
    #include "Flower.h"
    
    CFlower::CFlower(void)
        : _tp(0), _clr(0),
          _arg(0), _mx(false),
          _price(45.95)
    {
    }
    
    CFlower::CFlower(int type, int color,
                     int argn, bool mx,
                     double price)
        : _tp(type),
          _clr(color),
          _arg(argn),
          _mx(mx),
          _price(price)
    {
    }
    
    CFlower::~CFlower()
    {
    }
  9. On the main menu, click Project -> Add Class...
  10. In the Templates list, make sure C++ Class is selected and click Add
  11. Set the Name of the class to COrderProcessing and click Finish
  12. Complete the OrderProcessing.h header file as follows:
     
    #pragma once
    
    #include "Flower.h"
    
    public ref class COrderProcessing
    {
    private:
        int       _qty;
        CFlower ^ _flr;
    
    public:
        COrderProcessing(void);
        ~COrderProcessing();
    
        property CFlower ^ Flower
        {
            CFlower ^ get() { return _flr; }
            void set(CFlower ^ flr) { _flr = flr; }
        }
    
        property int Quantity
        {
            int get() { return _qty; }
            void set(int q)
            {
    		_qty = (q <= 0 ? 0 : q);
            }
        }
    
        double GetTotalPrice();
    };
  13. Complete the OrderProcessing.cpp source file as follows:
     
    #include "OrderProcessing.h"
    
    COrderProcessing::COrderProcessing(void)
    {
        _flr = gcnew CFlower;
    }
    
    COrderProcessing::~COrderProcessing()
    {
        delete _flr;
    }
    
    double COrderProcessing::GetTotalPrice()
    {
        return Quantity * _flr->UnitPrice;
    }
  14. To create one more source file, on the main menu, click Project -> Add New Item...
  15. In the Templates list, make sure C++ File (.cpp) is selected.
    Set the Name to Exercise and click Add
  16. Complete the file as follows:
     
    #include "Flower.h"
    #include "OrderProcessing.h"
    
    using namespace System; 
    
    COrderProcessing ^ CreateFlowerOrder()
    {
        double price;
        int arrangement;
        int type, color, qty, mx;
        COrderProcessing ^ order = gcnew COrderProcessing;
    
        Console::WriteLine(L"=======================");
        Console::WriteLine(L"==-=-=Flower Shop=-=-==");
        Console::WriteLine(L"-----------------------");
    
        Console::WriteLine(L"Enter the Type of Flower Order");
        Console::WriteLine(L"1. Roses");
        Console::WriteLine(L"2. Lilies");
        Console::WriteLine(L"3. Daisies");
        Console::WriteLine(L"4. Carnations");
        Console::WriteLine(L"5. Live Plant");
        Console::WriteLine(L"6. Mixed");
        Console::Write(L"Your Choice: ");
        type = int::Parse(Console::ReadLine());
    
        Console::WriteLine(L"Enter the Color");
        Console::WriteLine(L"1. Red");
        Console::WriteLine(L"2. White");
        Console::WriteLine(L"3. Yellow");
        Console::WriteLine(L"4. Pink");
        Console::WriteLine(L"5. Orange");
        Console::WriteLine(L"6. Blue");
        Console::WriteLine(L"7. Lavender");
        Console::WriteLine(L"8. Mixed");
        Console::Write(L"Your Choice: ");
        color = int::Parse(Console::ReadLine());
    
        Console::WriteLine(L"Enter the Type of Arrangement");
        Console::WriteLine(L"1. Bouquet");
        Console::WriteLine(L"2. Vase");
        Console::WriteLine(L"3. Basket");
        Console::WriteLine(L"4. Mixed");
        Console::Write(L"Your Choice: ");
        arrangement = int::Parse(Console::ReadLine());
    
        Console::Write(L"Is the Order Mixed (1=Yes/0=No)?");
        mx = int::Parse(Console::ReadLine());
    
        Console::Write(L"Enter the Unit Price: ");
        price = double::Parse(Console::ReadLine());
    
        Console::Write(L"Enter Quantity:       ");
        qty = int::Parse(Console::ReadLine());
    
        CFlower ^ flr = gcnew CFlower(type, color, arrangement,
    		                  mx = 1 ? true : false, price);
        order->Flower = flr;
        order->Quantity = qty;
    
        return order;
    }
    
    int main()
    {
        COrderProcessing ^ flower = CreateFlowerOrder();
    
        Console::WriteLine();
        return 0;
    }
  17. Save all

if…else if and if…else if…else

If you use an if...else conditional statement, you can process only two statements. In some cases, you may deal with more than two conditions. In this case, you can use an if...else if condition. Its formula is:

if(Condition1)
    Statement1;
else if(Condition2)
    Statement2;

The compiler would first check Condition1. If Condition1 is true, then Statement1 would be executed. If Condition1 is false, then the compiler would check Condition2. If Condition2 is true, then the compiler would execute Statement2. Any other result would be ignored. Here is an example:

using namespace System;

int main()
{
	__wchar_t TypeOfHome;

	Console::WriteLine(L"What Type of House Would you Like to Purchase?");
	Console::WriteLine(L"S - Single Family");
	Console::WriteLine(L"T - Town House");
	Console::WriteLine(L"C - Condominium");
	Console::Write(L"Your Choice? ");
	TypeOfHome = __wchar_t::Parse(Console::ReadLine());

	if( TypeOfHome == L'S' )
		Console::WriteLine(L"\nType of Home: Single Family");
	else if( TypeOfHome == L'T')
		Console::WriteLine(L"\nType of Home: Town House");
	
	Console::WriteLine();

	return 0;
}

Here is an example of running the program:

What Type of House Would you Like to Purchase?
S - Single Family
T - Town House
C - Condominium
Your Choice? S

Type of Home: Single Family

Press any key to continue . . .

Here is another example of running the program:

What Type of House Would you Like to Purchase?
S - Single Family
T - Town House
C - Condominium
Your Choice? W

Press any key to continue . . .

Notice that only two conditions are evaluated. Any condition other than these two is not considered. Because there can be other alternatives, the C++ language provides an alternate else as the last resort. Its formula is:

if(Condition1)
    Statement1;
else if(Condition2)
    Statement2;
else
    Statement-n;
if(Condition1)
    Statement1;
else if(Condition2)
    Statement2;
else if(Condition3)
    Statement3;
else
    Statement-n;

The compiler will check the first condition. If Condition1 is true, it will execute Statement1. If Condition1 is false, then the compiler will check the second condition. If Condition2 is true, it will execute Statement2. When the compiler finds a Condition-n to be true, it will execute its corresponding statement. It that Condition-n is false, the compiler will check the subsequent condition. This means you can include as many conditions as you see fit using the else if statement. If after examining all the known possible conditions you still think that there might be an unexpected condition, you can use the optional single else. Here is an example:

using namespace System;

int main()
{
	__wchar_t TypeOfHome;

	Console::WriteLine(L"What Type of House Would you Like to Purchase?");
	Console::WriteLine(L"S - Single Family");
	Console::WriteLine(L"T - Town House");
	Console::WriteLine(L"C - Condominium");
	Console::Write(L"Your Choice? ");
	TypeOfHome = __wchar_t::Parse(Console::ReadLine());

	if( TypeOfHome == L'S' )
		Console::WriteLine(L"\nType of Home: Single Family");
	else if( TypeOfHome == L'T')
		Console::WriteLine(L"\nType of Home: Town House");
	else if( TypeOfHome == L'C')
		Console::WriteLine(L"\nType of Home: Condominium");
	else
		Console::WriteLine(L"\nType of Home: Unknown");
	
	Console::WriteLine();

	return 0;
}

Here is an example of running the program:

What Type of House Would you Like to Purchase?
S - Single Family
T - Town House
C - Condominium
Your Choice? W

Type of Home: Unknown

Press any key to continue . . .

switch

The if...else if...else statement allows you to create a series of conditions that would be checked one after another until either a valid one is found or the compiler has to execute a statement that doesn't fit any of the conditions. Instead of checking each condition, the C++ language provides a technique presenting one condition and some available options. Instead of checking each condition, the compiler can be directly lead to the appropriate statement. This is done using a switch operator.

The switch statement considers a condition and executes a statement based on the possible outcome. 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 formula of the switch statement is:

switch(Expression)
{
    case Choice1:
        Statement1;
    case Choice2:
        Statement2;
    case Choice-n:
        Statement-n;
}

The expression to examine is an integer. Since an enumeration (enum) and the character (char) data types are just other forms of integers, they can be used too. Here is an example of using the switch statement:

using namespace System;

int main()
{
	int TypeOfHome;

	Console::WriteLine(L"What Type of House Would you Like to Purchase?");
	Console::WriteLine(L"1 - Single Family");
	Console::WriteLine(L"2 - Town House");
	Console::WriteLine(L"3 - Condominium");
	Console::Write(L"Your Choice? ");
	TypeOfHome = int::Parse(Console::ReadLine());

	switch(TypeOfHome)
	{
	case 1:
		Console::WriteLine(L"\nType of Home: Single Family");
	case 2:
		Console::WriteLine(L"\nType of Home: Town House");
	case 3:
		Console::WriteLine(L"\nType of Home: Condominium");
	}
	
	Console::WriteLine();

	return 0;
}

The program above would request a number from the user. If the user types 1, it would execute the first, the second, and the third cases. If the user types 2, the program would execute the second and third cases. If the user supplies 3, only the third case would be considered. If the user types any other number, no case would execute.

When establishing the possible outcomes that the switch statement should consider, at times there will be other 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 formula of the switch statement that considers the default case would be:

switch(Expression)
{
    case Choice1:
        Statement1;
    case Choice2:
        Statement2;
    case Choice-n:
        Statement-n;
    default:
        Other-Possibility;
}

Therefore another version of the program above would be:

using namespace System;

int main()
{
	int TypeOfHome;

	Console::WriteLine(L"What Type of House Would you Like to Purchase?");
	Console::WriteLine(L"1 - Single Family");
	Console::WriteLine(L"2 - Town House");
	Console::WriteLine(L"3 - Condominium");
	Console::Write(L"Your Choice? ");
	TypeOfHome = int::Parse(Console::ReadLine());

	switch(TypeOfHome)
	{
	case 1:
		Console::WriteLine(L"\nType of Home: Single Family");
	case 2:
		Console::WriteLine(L"\nType of Home: Town House");
	case 3:
		Console::WriteLine(L"\nType of Home: Condominium");
	default:
		Console::WriteLine(L"\nType of Home:: Unknown");
	}
	
	Console::WriteLine();

	return 0;
}

Previous Copyright © 2006-2016, FunctionX, Inc. Next