Home

Conditional Looping

 

Introduction

A loop is a type of conditional statement that keeps checking a condition and executing a statement until the condition is false.

while a Condition is True

One of the operators used to perform a loop is called while. Its formula is:

while(Condition) Statement;

To execute this expression, the compiler first examines the Condition. If the Condition is true, then it executes the Statement. After executing the Statement, the Condition is checked again. AS LONG AS the Condition is true, it will keep executing the Statement. When or once the Condition becomes false, it exits the loop:

While

Here is an example:

using namespace System;

int main()
{
	int Stories = 0;
	
	while( Stories <= 4 )
	{
		Console::WriteLine("Number {0}", Stories);
		Stories++;
	}
	
	Console::WriteLine();

	return 0;
}

This would produce:

Number 0
Number 1
Number 2
Number 3
Number 4

Press any key to continue . . .

To effectively execute a while condition, you should make sure you provide a mechanism for the compiler to use or get a reference value for the condition, variable, or expression being checked. This is sometimes in the form of a variable being initialized although it could be some other expression. Such a while condition could be illustrated as follows:

While

do This while a Condition is True

The while loop is used first check a condition and then execute a statement. If the condition is false, the statement would never execute. Consider the following program:

using namespace System;

int main()
{
	int Stories = 5;
	
	while( Stories <= 4 )
	{
		Console::WriteLine("Number {0}", Stories);
		Stories++;
	}
	
	Console::WriteLine();

	return 0;
}

When this program executes, nothing from the while loop would execute because, as the condition is checked in the beginning, it is false and the compiler would not get to the Statement. In some cases, you may want to execute a statement before checking the condition for the first time. This can be done using the do…while statement. Its formula is:

do Statement while (Condition);

The do…while condition executes a Statement first. After the first execution of the Statement, it examines the Condition. If the Condition is true, then it executes the Statement again. It will keep executing the Statement AS LONG AS the Condition is true. Once the Condition becomes false, the looping (the execution of the Statement) would stop.

If the Statement is a short one, such as made of one line, simply write it after the do keyword. Like the if and the while statements, the Condition being checked must be included between parentheses. The whole do…while statement must end with a semicolon.

do...while

Another version of the counting program seen previously would be:

using namespace System;

int main()
{
	int Stories = 0;
	
	do
		Console::WriteLine("Number {0}", Stories++);
	while( Stories <= 4 );
	
	Console::WriteLine();

	return 0;
}

This would produce:

Number 0
Number 1
Number 2
Number 3
Number 4

Press any key to continue . . .

If the Statement is long and should span more than one line, start it with an opening curly bracket "{" and end it with a closing curly bracket "}".

Practical LearningPractical Learning: Applying a do...while Loop

  1. To use a do...while loop, change the CreateStoreItem() function as follows:
     
    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());
    
        do {
            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());
        }while( (category < 1) || (category > 10) );
    
        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;
        }
    
        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;
    }
  2. Execute the application to test it
  3. Close the DOS window

for

The for statement is typically used to count a number of items. At its regular structure, it is divided in three parts. The first section specifies the starting point for the count. The second section sets the counting limit. The last section determines the counting frequency. The syntax of the for statement is:

for(Start; End; Frequency) Statement;

The Start expression is a variable assigned the starting value. This could be Count = 0;

The End expression sets the criteria for ending the counting. An example would be Count < 24; this means the counting would continue as long as the Count variable is less than 24. When the count is about to rich 24, because in this case 24 is excluded, the counting would stop. To include the counting limit, use the <= or >= comparison operators depending on how you are counting.

The Frequency expression would let the compiler know how many numbers to add or subtract before continuing with the loop. This expression could be an increment operation such as ++Count.

Here is an example that applies the for statement:

using namespace System;

int main()
{
	for(int Stories = 1; Stories <= 4; Stories++)
		Console::WriteLine("Number {0}", Stories);
	
	Console::WriteLine();

	return 0;
}

This would produce:

Number 1
Number 2
Number 3
Number 4

Press any key to continue . . .

 

 

Previous Copyright © 2006-2007 FunctionX, Inc. Next