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. |
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: |
Consider the following program: 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"); 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 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"); 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 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 . . .
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; } Console.WriteLine(); return 0; } } This would produce: Story 1 Story 2 Story 3 Press any key to continue . . . 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); } 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 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 . . .
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 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; 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; } }
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 method is: ReturnValue Function(Arguments, if any) { Optional Action . . . Function(); Optionan Action . . . } A recursive method starts with a return value. If it would not return a value, you can define it with void. After its name, the method can take one or more arguments. Most of the time, a recursive method takes at least one argument that it would then modify. In the body of the method, you can take the necessary actions. There are no particular steps to follow when implementing a recursive method but there are two main rules to observe:
For our example of counting decrementing odd numbers, you could start by creating a method 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 method, we will display the current value of the argument, subtract 2, and recall the method itself. Here is our function: using System; public class Exercise { static void OddNumbers(int a) { if (a >= 1) { Console.Write("{0}, ", a); a -= 2; OddNumbers(a); } } public static int Main() { const int Number = 9; Console.WriteLine("Odd Numbers"); OddNumbers(Number); Console.WriteLine(); return 0; } } Notice that the method calls itself in its body. This would produce: Odd Numbers 9, 7, 5, 3, 1, Press any key to continue . . .
Recursive methods 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 method 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 method can be implemented as follows: using System; public class Exercise { static int AdditionalOdd(int a) { if (a <= 1) return 1; return a + AdditionalOdd(a - 2); } static void OddNumbers(int a) { if (a >= 1) { Console.Write("{0}, ", a); a -= 2; OddNumbers(a); } } public static int Main() { const int Number = 9; Console.WriteLine("Odd Numbers"); OddNumbers(Number); Console.WriteLine(); Console.WriteLine("Sum of Odds: {0}\n", AdditionalOdd(Number)); return 0; } } This would produce: Odd Numbers 9, 7, 5, 3, 1, Sum of Odds: 25 Press any key to continue . . .
|
|
||
Previous | Copyright © 2008-2016, FunctionX, Inc. | Next |
|