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.
|
|
- Start Microsoft Visual Studio
- To create a new application, on the main menu, click File -> New Project...
- In the middle list, click Empty Project
- Change the Name to NationalBank4 and press Enter
- To create a new file, on the main menu, click Project -> Add New Item...
- In the middle list, click Code File
- Change the Name of the file to Customer
- Click Add
- Complete the Customer.cs file as follows:
public enum AccountType { Checking, Saving, Other } public class Customer { public string AccountNumber; public AccountType Type; public string FullName; public double Balance; public short PIN; public Customer(string acnt = "000-000000-000", AccountType category = AccountType.Other, string name = "John Doe") { AccountNumber = acnt; Type = category; FullName = name; PIN = 0; Balance = 0.00D; } }
- To create a new file, in the Solution Explorer, right-click NationalBank4 -> Add -> New Item...
- In the middle list, make sure Code File is selected.
Change the Name to Management and press Enter - Complete the file as follows:
using System; public class Management { private Customer CreateNewAccount() { byte typeOfAccount = 0; Customer client = new Customer(); Console.WriteLine("==========================================="); Console.WriteLine("==-= National Bank =-======================"); Console.WriteLine("-------------------------------------------"); Console.Write("Enter a number for the new account(000-000000-000): "); client.AccountNumber = Console.ReadLine(); Console.WriteLine("What type of account the customer wants to open"); Console.WriteLine("1 - Checking Account"); Console.WriteLine("2 - Savings Account"); Console.Write("Enter account type: "); typeOfAccount = byte.Parse(Console.ReadLine()); if (typeOfAccount == 1) client.Type = AccountType.Checking; else if (typeOfAccount == 2) client.Type = AccountType.Saving; else client.Type = AccountType.Other; Console.Write("Enter customer name: "); client.FullName = Console.ReadLine(); Console.Write("Ask the customer to enter a PIN: "); client.PIN = short.Parse(Console.ReadLine()); return client; } public double GetMoney() { double amount = 0; Console.Write("Amount: "); amount = double.Parse(Console.ReadLine()); return amount; } private void ShowAccountInformation(Customer cust) { Console.WriteLine("==========================================="); Console.WriteLine("==-= National Bank =-======================"); Console.WriteLine("Customer Account Information"); Console.WriteLine("-------------------------------------------"); Console.WriteLine("Account #: {0}", cust.AccountNumber); Console.WriteLine("Account Type: {0}", cust.Type); Console.WriteLine("Full Name: {0}", cust.FullName); Console.WriteLine("PIN #: {0}", cust.PIN); Console.WriteLine("Balance: {0:F}", cust.Balance); Console.WriteLine("==========================================="); } public static int Main() { return 0; } }
while a Condition is True
|
One of the operators used to perform a loop is called
while. To create a while loop:
- Use the following formula:
while(Condition) Statement;
- Right-click the section where you want to add it and click Insert Snippet... Double-click Visual C#. In the list, double-click while
To execute a while condition, 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 System; public class Exercise { public static int Main() { var stories = 0; while( stories <= 4 ) { Console.WriteLine("Number {0}", stories); stories++; } 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:
|
- Change the Management.cs file as follows:
using System; public class Management { private Customer CreateNewAccount() { . . . No Change public static int Main() { int? Counter = 1; Customer accountHolder = null; Management registration = new Management(); Console.Title = "National Bank"; while (Counter < 5) { accountHolder = registration.CreateNewAccount(); Console.WriteLine("Enter the customer's initial deposit"); accountHolder.Balance = registration.GetMoney(); Console.Clear(); registration.ShowAccountInformation(accountHolder); Counter++; Console.WriteLine("Press Enter for Next Action"); Console.ReadKey(); Console.Clear(); } return 0; } }
- Press F5 to execute
- Enter information as follows:
Account # 202-410443-240 Account Type: 1 Customer Name: Paul Martin Eloundou PIN: 8402 Initial Deposit: 750 Account #: 202-103344-042 Account Type: 2 Customer Name: Jimmy Simms PIN: 2468 Initial Deposit 500 Account # 410-240301-443 Account Type: 2 Customer Name: Eya Miri PIN: 1119 Initial Deposit: 1500 Account # 718-202404-240 Account Type: 1 Customer Name: Alain Gassila PIN: 2226 Initial Deposit: 220.8 - Press Enter
- Press Enter to close the DOS window and return to your programming environment
The while loop is used to first check a condition
and then execute a statement. If the condition is false, the statement would
never execute. Consider the following program:
using System;
public class Exercise
{
public static int Main()
{
var stories = 5;
while (stories <= 4)
{
Console.WriteLine("Number {0}", stories);
stories++;
}
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 System;
public class Exercise
{
public static int Main()
{
var stories = 0;
do
Console.WriteLine("Number {0}", stories++);
while (stories <= 4);
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 "}".
|
- Change the Management.cs file as follows:
using System; public class Management { . . . No Change public static int Main() { double amount = 0; byte nextAction = 0; Customer accountHolder = null; Management registration = new Management(); Console.Title = "National Bank"; accountHolder = registration.CreateNewAccount(); Console.WriteLine("Enter the customer's initial deposit"); accountHolder.Balance = registration.GetMoney(); Console.Clear(); registration.ShowAccountInformation(accountHolder); do { Console.WriteLine("What do you want to do now?"); Console.WriteLine("1 - Check account balance"); Console.WriteLine("2 - Make a deposit"); Console.WriteLine("3 - Withdraw money"); Console.WriteLine("4 - Transfer money from one account to another"); nextAction = byte.Parse(Console.ReadLine()); } while ((nextAction < 1) || (nextAction > 4)); switch (nextAction) { case 1: break; case 2: Console.Write("Enter the Deposit "); amount = double.Parse(Console.ReadLine()); accountHolder.Balance = accountHolder.Balance + amount; break; case 3: Console.Write("Enter the Withdrawal "); amount = double.Parse(Console.ReadLine()); accountHolder.Balance = accountHolder.Balance - amount; break; case 4: Console.WriteLine("Operation not available: You have only one account with us"); break; } registration.ShowAccountInformation(accountHolder); Console.ReadKey(); return 0; } }
- Press F5 to execute
- When requested, type the values as follows:
Account Number: 301-240410-202 Account Type: 1 Customer Name: Frank Trombs PIN: 9731 Initial Deposit: 40.1 - Press Enter
=========================================== ==-= National Bank =-====================== Customer Account Information ------------------------------------------- Account #: 301-240410-202 Account Type: Checking Full Name: Frank Trombs PIN #: 9731 Balance: 40.10 =========================================== What do you want to do now? 1 - Check account balance 2 - Make a deposit 3 - Withdraw money 4 - Transfer money from one account to another Enter your choice:
- When asked what you want to do, type 2 to make a deposit and press Enter
- Type 125.85 and press Enter
=========================================== ==-= National Bank =-====================== Customer Account Information ------------------------------------------- Account #: 301-240410-202 Account Type: Checking Full Name: Frank Trombs PIN #: 9731 Balance: 165.95 ===========================================
- Press Enter to close the DOS window and return top your programming environment
- Close your programming environment
Controlling the Conditional Statements
|
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:
Here is an example that applies the for statement:
using System;
public class Exercise
{
public static int Main()
{
for (var stories = 0; stories <= 4; stories++)
Console.WriteLine("Number {0}", stories);
return 0;
}
}
This would produce:
Number 1 Number 2 Number 3 Number 4 Press any key to continue . . .
Nesting a Conditional Statement
|
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"); 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");
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 . . .
|
- Change the Management.csc file as follows:
using System; public class Management { private Customer CreateNewAccount() { . . . No Change return client; } public double GetMoney() { double amount = 0; Console.Write("Amount: "); amount = double.Parse(Console.ReadLine()); return amount; } private void ShowAccountInformation(Customer cust) { Console.WriteLine("==========================================="); Console.WriteLine("==-= National Bank =-======================"); Console.WriteLine("Customer Account Information"); Console.WriteLine("-------------------------------------------"); Console.WriteLine("Account #: {0}", cust.AccountNumber); Console.WriteLine("Account Type: {0}", cust.Type); Console.WriteLine("Full Name: {0}", cust.FullName); Console.WriteLine("PIN #: {0}", cust.PIN); Console.WriteLine("Balance: {0:F}", cust.Balance); Console.WriteLine("==========================================="); } public static int Main() { double amount = 0; byte nextAction = 0; Customer accountHolder = null; Management registration = new Management(); Console.Title = "National Bank"; accountHolder = registration.CreateNewAccount(); Console.WriteLine("Enter the customer's initial deposit"); accountHolder.Balance = registration.GetMoney(); Console.Clear(); registration.ShowAccountInformation(accountHolder); do { Console.WriteLine("What do you want to do now?"); Console.WriteLine("1 - Check account balance"); Console.WriteLine("2 - Make a deposit"); Console.WriteLine("3 - Withdraw money"); Console.WriteLine("4 - Transfer money from one account to another"); Console.Write("Enter your choice: "); nextAction = byte.Parse(Console.ReadLine()); Console.Clear(); switch (nextAction) { case 1: Console.Clear(); registration.ShowAccountInformation(accountHolder); Console.Write("Press Enter for next operation"); Console.ReadKey(); break; case 2: Console.Write("Enter Deposit "); amount = registration.GetMoney(); accountHolder.Balance = accountHolder.Balance + amount; Console.Clear(); registration.ShowAccountInformation(accountHolder); break; case 3: Console.Write("Enter Withdrawal "); amount = registration.GetMoney(); if (amount > accountHolder.Balance) { Console.WriteLine( "You are not allowed to withdraw more money than your account has."); Console.ReadKey(); } else accountHolder.Balance = accountHolder.Balance - amount; Console.Clear(); registration.ShowAccountInformation(accountHolder); break; case 4: Console.WriteLine( "Operation not available: You have only one account with us"); break; } if ((nextAction < 1) || (nextAction > 4)) Console.WriteLine( "Invalid Action: Please enter a value between 1 and 4"); } while ((nextAction >= 1) && (nextAction <= 4)); Console.ReadKey(); return 0; } }
- Press F5 to execute
- Enter information as follows:
Account # 202-410443-240 Account Type: 1 Customer Name: Paul Martin Eloundou PIN: 8402 Initial Deposit: 750 - Press Enter
=========================================== ==-= National Bank =-====================== Customer Account Information ------------------------------------------- Account #: 202-410443-240 Account Type: Checking Full Name: Paul Martin Eloundou PIN #: 8402 Balance: 750.00 =========================================== What do you want to do now? 1 - Check account balance 2 - Make a deposit 3 - Withdraw money 4 - Transfer money from one account to another Enter your choice:
- When asked to specify the next action, type 3 to withdraw money and press Enter
- Type 425.85 as the amount to withdraw and press
Enter
=========================================== ==-= National Bank =-====================== Customer Account Information ------------------------------------------- Account #: 202-410443-240 Account Type: Checking Full Name: Paul Martin Eloundou PIN #: 8402 Balance: 324.15 =========================================== What do you want to do now? 1 - Check account balance 2 - Make a deposit 3 - Withdraw money 4 - Transfer money from one account to another Enter your choice:
- Type the next action as 2 and press Enter
- Type the amount as 22.84 and press Enter
=========================================== ==-= National Bank =-====================== Customer Account Information ------------------------------------------- Account #: 202-410443-240 Account Type: Checking Full Name: Paul Martin Eloundou PIN #: 8402 Balance: 346.99 =========================================== What do you want to do now? 1 - Check account balance 2 - Make a deposit 3 - Withdraw money 4 - Transfer money from one account to another Enter your choice:
- Type the next action as 3 and press Enter
- Type the amount to withdraw as 500 and press Enter
Enter Withdrawal Amount: 500 You are not allowed to withdraw more money than your account has.
- Press Enter
=========================================== ==-= National Bank =-====================== Customer Account Information ------------------------------------------- Account #: 202-410443-240 Account Type: Checking Full Name: Paul Martin Eloundou PIN #: 8402 Balance: 346.99 =========================================== What do you want to do now? 1 - Check account balance 2 - Make a deposit 3 - Withdraw money 4 - Transfer money from one account to another Enter your choice:
- Type 0 and press Enter
- Press Enter again to close the DOS window and return to your programming environment
When you start creating client/server or resource
intensive applications, you will know it is possible for more than one user
or for more than one resource to access your application or to try to
perform an operation on an object of your program. An example would consist
of two people trying to add a new record or a new line to the same file. In
some cases you can allow the operation. In some other cases, you will want
to prevent it.
To prevent more than one user or resource to access an
object of your application, you must create a lock where the operation is
not allowed. To do this, use the following formula:
Declare a Variable lock(Variable) { // Do what you want here } // The variable has been released
|
- Change the Management.cs file as follows:
using System; public class Management { . . . No Change public static int Main() { double amount = 0; byte nextAction = 0; Customer accountHolder = null; Management registration = new Management(); Console.Title = "National Bank"; accountHolder = registration.CreateNewAccount(); Console.WriteLine("Enter the customer's initial deposit"); accountHolder.Balance = registration.GetMoney(); Console.Clear(); registration.ShowAccountInformation(accountHolder); do { Console.WriteLine("What do you want to do now?"); Console.WriteLine("1 - Check account balance"); Console.WriteLine("2 - Make a deposit"); Console.WriteLine("3 - Withdraw money"); Console.WriteLine("4 - Transfer money from one account to another"); Console.Write("Enter your choice: "); nextAction = byte.Parse(Console.ReadLine()); Console.Clear(); // Don't allow wny other operation on this section // while this section is executing lock (registration) { switch (nextAction) { case 1: Console.Clear(); registration.ShowAccountInformation(accountHolder); Console.Write("Press Enter for next operation"); Console.ReadKey(); break; case 2: Console.Write("Enter Deposit "); amount = registration.GetMoney(); accountHolder.Balance = accountHolder.Balance + amount; Console.Clear(); registration.ShowAccountInformation(accountHolder); break; case 3: Console.Write("Enter Withdrawal "); amount = registration.GetMoney(); if (amount > accountHolder.Balance) { Console.WriteLine( "You are not allowed to withdraw more money than your account has."); Console.ReadKey(); } else accountHolder.Balance = accountHolder.Balance - amount; Console.Clear(); registration.ShowAccountInformation(accountHolder); break; case 4: Console.WriteLine( "Operation not available: You have only one account with us"); break; } } // Other objects can access this section now if ((nextAction < 1) || (nextAction > 4)) Console.WriteLine("Invalid Action: Please enter a value between 1 and 4"); } while ((nextAction >= 1) && (nextAction <= 4)); Console.ReadKey(); return 0; } }
- Press F5 to execute
- Follow the same steps of the previous section
- Return to your programming environment
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;
}
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);
}
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.
Inside a loop, you may want to put a flag that would
monitor the evolution of a tag so that, if the tag gets to a certain value,
instead of skipping the looping by 1, you can make it jump to a valued range
of your choice. To do this, in the loop, check the current value and if it
gets to one you are looking for, change it. Here is an example where a loop
is asked to count from 0 to 15:
using System; public class Exercise { static int Main() { for (var story = 0; story < 15; story++) { if (story == 6) story = 10; Console.WriteLine("Elevator at: {0}", story); } return 0; } }
This would produce:
Elevator at: 0 Elevator at: 1 Elevator at: 2 Elevator at: 3 Elevator at: 4 Elevator at: 5 Elevator at: 10 Elevator at: 11 Elevator at: 12 Elevator at: 13 Elevator at: 14 Press any key to continue . . .
Notice that, when the loop reaches 6, it is asked to
jump to number 10 instead.
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 . . .
|
- Change the Management.cs file as follows:
using System; public class Management { . . . No Change public static int Main() { . . . No Change registration.ShowAccountInformation(accountHolder); do { . . . No Change lock (registration) { switch (nextAction) { case 0: goto EndTime; break; case 1: Console.Clear(); registration.ShowAccountInformation(accountHolder); Console.Write("Press Enter for next operation"); Console.ReadKey(); break; . . . No Change } } if ((nextAction < 1) || (nextAction > 4)) Console.WriteLine("Invalid Action: Please enter a value between 1 and 4"); } while ((nextAction >= 1) && (nextAction <= 4)); EndTime: Console.ReadKey(); return 0; } }
- Press F5 to execute
- Enter information as follows:
Account #: 202-103344-042 Account Type: 2 Customer Name: Jimmy Simms PIN: 2468 Initial Deposit 500 - Press Enter
=========================================== ==-= National Bank =-====================== Customer Account Information ------------------------------------------- Account #: 202-103344-042 Account Type: Saving Full Name: Jimmy Simms PIN #: 2468 Balance: 500.00 =========================================== What do you want to do now? 1 - Check account balance 2 - Make a deposit 3 - Withdraw money 4 - Transfer money from one account to another Enter your choice:
- When asked to specify the next action, type 2 to make a deposit and press Enter
- Type 328.66 as the amount to deposit and press
Enter
=========================================== ==-= National Bank =-====================== Customer Account Information ------------------------------------------- Account #: 202-103344-042 Account Type: Saving Full Name: Jimmy Simms PIN #: 2468 Balance: 828.66 =========================================== What do you want to do now? 0 - Close the application 1 - Check account balance 2 - Make a deposit 3 - Withdraw money 4 - Transfer money from one account to another Enter your choice:
- For the next action, type 0 and press Enter
- Press Enter to close the DOS window and return to your programming environment
- Close your programming environment
No comments:
Post a Comment