Introduction to >Counting and Looping
Introduction to >Counting and Looping
Conditional Looping
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:
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:
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.
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 Learning: Applying a do...while Loop |
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; }
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 . . .
Controlling the Conditional Statements |
Nesting a Conditional Statement |
Consider the following program:
using namespace System; int main() { int TypeOfHome; do { 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()); } while( (TypeOfHome < 1) || (TypeOfHome > 3) ); if( TypeOfHome == 1 ) Console::WriteLine(L"\nType of Home: Single Family"); else if( TypeOfHome == 2 ) Console::WriteLine(L"\nType of Home: Town House"); else if( TypeOfHome == 3 ) Console::WriteLine(L"\nType of Home: Condominium"); Console::WriteLine(); 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 namespace System; int main() { int TypeOfHome; do { 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()); if( (TypeOfHome < 1) || (TypeOfHome > 3) ) Console::WriteLine(L"Invalid Choice: Please try againe"); } while( (TypeOfHome < 1) || (TypeOfHome > 3) ); if( TypeOfHome == 1 ) Console::WriteLine(L"\nType of Home: Single Family"); else if( TypeOfHome == 2 ) Console::WriteLine(L"\nType of Home: Town House"); else if( TypeOfHome == 3 ) Console::WriteLine(L"\nType of Home: Condominium"); Console::WriteLine(); return 0; }
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 . . .
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 namespace System; int main() { for(int Stories = 1; Stories <= 12; Stories++) { Console::WriteLine("Story {0}", Stories); if( Stories == 3 ) break; } Console::WriteLine(); return 0; }
This would produce:
Story 1 Story 2 Story 3 Press any key to continue . . .
Consider an example we used for 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"); default: 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? 1 - Single Family 2 - Town House 3 - Condominium Your Choice? 1 Type of Home: Single Family Type of Home: Town House Type of Home: Condominium Type of Home:: Unknown Press any key to continue . . .
Notice that, although the user would have entered 1, the other cases would have executed as well. The break statement can be used to handle the cases in a switch statement. For example, it can be used to stop execute when a valid case has been found. To use it, before the end of a case, execute the break statement. The above program can better be written as follows:
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"); break; case 2: Console::WriteLine(L"\nType of Home: Town House"); break; case 3: Console::WriteLine(L"\nType of Home: Condominium"); break; default: Console::WriteLine(L"\nType of Home:: Unknown"); } Console::WriteLine(); return 0; }
Here is an example of executing the program:
What Type of House Would you Like to Purchase? 1 - Single Family 2 - Town House 3 - Condominium Your Choice? 1 Type of Home: Single Family Press any key to continue . . .
Practical Learning: Applying a break |
void DescribeStoreItem(CStoreItem ^ %item) { Console::WriteLine(L"Store Item Description"); Console::WriteLine(L"Item Number: {0}", item->ItemNumber); switch(item->Category) { case ItemsCategories::Unknown: Console::WriteLine(L"Category: Uknown"); break; case ItemsCategories::CablesAndConnectors: Console::WriteLine(L"Category: Cables & Connectors"); break; case ItemsCategories::CellPhonesAndAccessories: Console::WriteLine(L"Category: Cell Phones & Accessories"); break; case ItemsCategories::Headphones: Console::WriteLine(L"Category: Headphones/Headsets"); break; case ItemsCategories::DigitalCameras: Console::WriteLine(L"Category: Digital Cameras"); break; case ItemsCategories::PDAsAndAccessories: Console::WriteLine(L"Category: PDAs & Accessories"); break; case ItemsCategories::TelephonesAndAccessories: Console::WriteLine(L"Category: Telephones & Accessories"); break; case ItemsCategories::TVsAndVideos: Console::WriteLine(L"Category: TVs and Videos - Plasma / LCD"); break; case ItemsCategories::SurgeProtectors: Console::WriteLine(L"Category: Surge Protectors"); break; case ItemsCategories::Instructional: Console::WriteLine(L"Category: " L"Instructional and Tutorials (VHS & DVD)TVs and Videos"); break; } Console::WriteLine(L"Make {0}", item->Make); Console::WriteLine(L"Model: {0}", item->Model); Console::WriteLine(L"Unit Price: {0:C}", item->UnitPrice); } 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 namespace System; int main() { for(int Stories = 1; Stories <= 6; Stories++) { if( Stories == 3 ) continue; Console::WriteLine("Story {0}", Stories); } Console::WriteLine(); 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. 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 namespace System; int main() { for(int Stories = 1; Stories <= 14; Stories++) { if( Stories == 4 ) goto CountUpTo3; Console::WriteLine("Story {0}", Stories); } CountUpTo3: Console::WriteLine(L"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 . . .
After creating an enumeration, its becomes a type of data. As such, it can be returned from a function. To start, you can precede the name of a function with the name of an enumeration to indicate that it is the type it would return. As compared to native types, you cannot just request the value of an enumeration from the user. This means that, most of the time, you should perform some processing in the body of the function and then return a value that is of the type of the enumeration. When a function returns an enumeration, you can use its return value the same way you would use a member of the enumeration.
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(L"\nType of Home: Single Family"); break; case TownHouse: Console::WriteLine(L"\nType of Home: Town House"); break; case Condominium: Console::WriteLine(L"\nType of Home: Condominium"); break; case Unknown: Console::WriteLine(L"\nType of Home:: Unknown"); break; } Console::WriteLine(); return 0; } HouseType GetHouseType() { int type; 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? "); type = int::Parse(Console::ReadLine()); if( type == 1 ) return SingleFamily; else if( type == 2 ) return TownHouse; else if( type == 3 ) return Condominium; } This GetHouseType() function indicates when one of three values is returned. In reality, this function could get a value other than the three that are considered. If the user enters such a value, the current version of the function would not know what to do. For this reason, the compiler would display a warning: warning C4715: 'GetHouseType' : not all control 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 namespace System; enum HouseType { Unknown, SingleFamily, TownHouse, Condominium }; HouseType GetHouseType(); int main() { HouseType TypeOfHouse; TypeOfHouse = GetHouseType(); switch(TypeOfHouse) { case SingleFamily: Console::WriteLine(L"\nType of Home: Single Family"); break; case TownHouse: Console::WriteLine(L"\nType of Home: Town House"); break; case Condominium: Console::WriteLine(L"\nType of Home: Condominium"); break; case Unknown: Console::WriteLine(L"\nType of Home:: Unknown"); break; } Console::WriteLine(); return 0; } HouseType GetHouseType() { int type; 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? "); type = int::Parse(Console::ReadLine()); if( type == 1 ) return SingleFamily; else if( type == 2 ) return TownHouse; else if( type == 3 ) return Condominium; return Unknown; }
Imagine that you want to count the positive odd numbers from a certain maximum to a certain minimum. For example, to count the odd numbers from 1 to 9, you would use: 9, 7, 5, 3, and 1 Notice that, to perform this operation, you consider the highest. Then you subtract 2 to get the previous. Again, you subtract 2 from the number to get the previous. What you are simply doing is to subtract a constant to what you already have and you invent very little. In computer programming, you can solve this type of problem by first writing a function, and then have the function call itself. This is the basis for recursion.
A type of formula to create a recursive function is: ReturnValue Function(Arguments, if any) { Optional Action . . . Function(); Optionan Action . . . } A recursive function starts with a return value. If it would not return a value, you can define it with void. After its name, the function can take one or more arguments. Most of the time, a recursive function takes at least one argument that it would then modify. In the body of the function, you can take the necessary actions. There are no particular steps to follow when implementing a recursive function but there are two main rules to observe:
For our example of counting decrementing odd numbers, you could start by creating a function that takes an integer as argument. To exercise some control on the lowest possible values, we will consider only positive numbers. In the body of the function, we will display the current value of the argument, subtract 2, and recall the function itself. Here is our function: using namespace System; void OddNumbers(int a) { if( a >= 1 ) { Console::Write(L"{0}, ", a); a -= 2; OddNumbers(a); } } int main() { const int Number = 9; Console::WriteLine(L"Odd Numbers"); OddNumbers(Number); Console::WriteLine(); return 0; } Notice that the function calls itself in its body. This would produce: Odd Numbers 9, 7, 5, 3, 1, Press any key to continue . . .
Recursive functions provide a valuable mechanism for building lists or series, which are value that are either increment or decrement but follow a pattern. Imagine that, instead of simply displaying odd numbers as we did above, you want to add them incrementally. If you have 1, it would also produce 1. If you have 5, you would like to add 1 to 3, then the result to 5, and so on. This can be illustrated as follows:
To perform this operation, you would consider 1. If the number is less than or equal to 1, the function should return 1. Otherwise, add 2 to 1, then add 2 to the new result. Continue this until you get to the value of the argument. The function can be implemented as follows: using namespace System; int AdditionalOdd(int a) { if( a <= 1 ) return 1; return a + AdditionalOdd(a - 2); } void OddNumbers(int a) { if( a >= 1 ) { Console::Write(L"{0}, ", a); a -= 2; OddNumbers(a); } } int main() { const int Number = 9; Console::WriteLine(L"Odd Numbers"); OddNumbers(Number); Console::WriteLine(); Console::WriteLine(L"Sum of Odds: {0}", AdditionalOdd(Number)); Console::WriteLine(); return 0; } This would produce: Odd Numbers 9, 7, 5, 3, 1, Sum of Odds: 25 Press any key to continue . . .
|