Showing posts with label csharp4. Show all posts
Showing posts with label csharp4. Show all posts

Thursday, June 6, 2013

Methods and Conditional Statements

Issues on Methods and Conditional Statements

 
Returning From a Method

So far, when defining a void method, we did not return a value. Here is an example:
using System;

public class Exercise
{
private void Show()
{
Console.WriteLine("C# Programming is fun!!!");
}


public static int Main()
{
Exercise exo = new Exercise();

exo.Show();
return 0;
}
}
 
In reality a void method can perform a return, as long as it does not return a true value. This is used to signal to the compiler that it is time to get out of the method. To add such as flag, in the appropriate section of the void method, simply type return;. Here is an example:
using System;

public class Exercise
{
private void Show()
{
Console.WriteLine("C# Programming is fun!!!");

return;
}

public static int Main()
{
Exercise exo = new Exercise();

exo.Show();
return 0;
}
}
In this case, the return; operation doesn't serve any true purpose. In the next section, we will see how it can be made useful when associated with a conditional statement.

ApplicationApplication: Introducing Methods and Conditions

  1. Start Microsoft Visual Studio
  2. To create a new application, on the main menu, click File -> New Project...
  3. In the middle list, click Empty Project
  4. Change the Name to NationalBank5 and press Enter
  5. To create a new file, on the main menu, click Project -> Add New Item...
  6. In the middle list, click Code File
  7. Change the Name of the file to Customer
  8. Click Add
  9. 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;
    }
    }
  10. To create a new file, in the Solution Explorer, right-click NationalBank5 -> Add -> New Item...
  11. In the middle list, make sure Code File is selected.
    Change the Name to Management and press Enter
  12. 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("===========================================");
    return;
    }

    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;
    }
    }
Conditional Return

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;

}
}
ApplicationApplication: Conditionally Returning a Value

  1. Change the Management.cs file as follows:
    using System;

    public class Management
    {
    private AccountType SpecifyAccountType()
    {
    byte type = 0;

    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: ");
    type = byte.Parse(Console.ReadLine());

    if (type == 1)
    return AccountType.Checking;
    else if (type == 2)
    return AccountType.Saving;
    else
    return AccountType.Other;
    }


    private Customer CreateNewAccount()
    {
    Customer client = new Customer();

    . . . No Change

    return client;
    }

    public double Deposit()
    {
    double amount = 0;

    Console.Write("Amount to deposit: ");
    amount = double.Parse(Console.ReadLine());

    return amount;
    }

    public double Withdraw(Customer cust)
    {
    double amount = 0;

    Console.Write("Amount to withdraw: ");
    amount = double.Parse(Console.ReadLine());

    if (amount > cust.Balance)
    {
    Console.WriteLine(
    "You are not allowed to withdraw more money than your account has.");
    Console.ReadKey();
    return 0.00D;
    }
    else
    return amount;
    }


    private void ShowAccountInformation(Customer cust)
    {
    . . . 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.Deposit();
    Console.Clear();

    registration.ShowAccountInformation(accountHolder);

    do
    {
    Console.WriteLine("What do you want to do now?");
    Console.WriteLine("0 - Close the application");
    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:
    amount = registration.Deposit();
    accountHolder.Balance += amount;

    Console.Clear();
    registration.ShowAccountInformation(accountHolder);
    break;

    case 3:
    amount = registration.Withdraw(accountHolder);
    accountHolder.Balance -= amount;

    Console.Clear();
    registration.ShowAccountInformation(accountHolder);
    break;

    case 4:
    Console.WriteLine(
    "Operation not available: You have only one account with us");
    break;

    default:
    return 0;
    }

    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;
    }
    }
  2. Press F5 to execute
  3. Enter information as follows:
     
    Account #: 257-484902-444
    Account Type: 1
    Customer Name: Josh Nay
    PIN: 5008
    Initial Deposit 250
    ===========================================
    ==-= National Bank =-======================
    -------------------------------------------
    New Account Number (000-000000-000): 257-484902-444
    What type of account the customer wants to open
    1 - Checking Account
    2 - Savings Account
    Enter account type: 1
    Enter customer name: Josh Nay
    Ask the customer to enter a PIN: 5008
    Enter the customer's initial deposit
    Amount to deposit: 250
  4. Press Enter
    ===========================================
    ==-= National Bank =-======================
    Customer Account Information
    -------------------------------------------
    Account #: 257-484902-444
    Account Type: Checking
    Full Name: Josh Nay
    PIN #: 5008
    Balance: 250.00
    ===========================================
    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:
  5. When asked to specify the next action, type 3 to withdraw money and press Enter
  6. Type 164.37 as the amount to deposit and press Enter
    ===========================================
    ==-= National Bank =-======================
    Customer Account Information
    -------------------------------------------
    Account #: 257-484902-444
    Account Type: Checking
    Full Name: Josh Nay
    PIN #: 5008
    Balance: 85.63
    ===========================================
    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:
  7. For the next action, type 2 and press Enter
  8. Type 116.18 as the amount to deposit and press Enter
    ===========================================
    ==-= National Bank =-======================
    Customer Account Information
    -------------------------------------------
    Account #: 257-484902-444
    Account Type: Checking
    Full Name: Josh Nay
    PIN #: 5008
    Balance: 201.81
    ===========================================
    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:
  9. For the next action, type 3 and press Enter
  10. Type 300 as the amount to withdraw and press Enter
    Amount to withdraw: 300
    You are not allowed to withdraw more money than your account has.
  11. Press Enter
  12. Type 0 as the next action and press Enter
while(true)

For the different situations in which we used a while condition so far, we included a means of checking the condition. Instead, you can include juste the true Boolean constant in the parentheses of true. Here is an example:
using System;

public class Exercise
{
public static int Main()
{
while (true)
Console.WriteLine("C# Programming is fun!!!");

return 0;
}
}
This type of statement is legal and would work fine. But it has no way of stopping because it is telling the compiler "As long as this is true, ...". The question is, what is "this"? As a result, the program would run for ever. Therefore, if you create a while(true) condition, in the body of the statement, you should provide a way for the compiler to stop, that is, a way for The condition to be false. This can be done by include an if condition. Here is an example:
using System;

public class Exercise
{
public static int Main()
{
int i = 0;

while (true)
{
if (i > 8)
break;
Console.WriteLine("C# Programming is fun!!!");

i++;
}

return 0;
}
}
This time, the program is asking the compiler to keep displaying a sentence in the console screen by counting from 0 and up; but if the count reaches 8, to stop. The above program would produce:
C# Programming is fun!!!
C# Programming is fun!!!
C# Programming is fun!!!
C# Programming is fun!!!
C# Programming is fun!!!
C# Programming is fun!!!
C# Programming is fun!!!
C# Programming is fun!!!
C# Programming is fun!!!
Press any key to continue . . .
In the above program, we used a break operator. You can use any other mechanism that can stop the looping, as long as at one time the condition would be false. Therefore, here is another way of stopping a while(true) loop:
using System;

public class Exercise
{
public static int Main()
{
int i = 0;

while (true)
{
if (i < 8)
Console.WriteLine("C# Programming is fun!!!");
else
return 0;

i++;
}
}
}
This would produce the same result as previously.
Instead of using while(true), you can first declare and initialize a Boolean variable, or you can use a Boolean variable whose value is already known. The value can come from a method or by other means.

ApplicationApplication: Using while(true)

  1. To start a new application, on the main menu, click File -> New Project...
  2. In the middle list, click Empty Project
  3. Change the name to DepartmentStore8
  4. To create a new class, on the main menu, click Project -> Add Class...
  5. Change the Name to StoreItem and click Add
  6. Change the document as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace DepartmentStore8
    {
    public class StoreItem
    {
    public int itemNumber;
    public string itemName;
    public string itemSize;
    public decimal unitPrice;

    public StoreItem()
    {
    itemNumber = 0;
    itemName = "";
    itemSize = "";
    unitPrice = 0.00M;
    }

    public StoreItem(int code, string name,
    string size, decimal price)
    {
    itemNumber = code;
    itemName = name;
    itemSize = size;
    unitPrice = price;
    }
    }
    }
  7. In the Solution Explorer, right-click DepartmentStore8 -> Add -> New Item...
  8. In the middle list, click Code File
  9. Change the Name to Inventory and press Enter
  10. Change the file as follows:
    using System;
    using DepartmentStore8;

    public class Inventory
    {
    static int Main()
    {
    StoreItem si = null;
    bool itemIsValid = true;

    Console.Title = "Department Store Inventory";
    Console.WriteLine("Department Store Inventory");
    while (itemIsValid)
    {
    si = new StoreItem();

    Console.WriteLine("------------------------");
    Console.Write("Enter Item #: ");
    si.itemNumber = int.Parse(Console.ReadLine());
    if (si.itemNumber < 0)
    itemIsValid = false;
    else
    {
    Console.Write("Enter Item Name: ");
    si.itemName = Console.ReadLine();
    Console.Write("Enter Item Size: ");
    si.itemSize = Console.ReadLine();
    Console.Write("Enter Unit Price: ");
    si.unitPrice = decimal.Parse(Console.ReadLine());

    Console.WriteLine("=-= Store Item =-=");
    Console.WriteLine("Item #: {0}", si.itemNumber);
    Console.WriteLine("Item Name: {0}", si.itemName);
    Console.WriteLine("Size: {0}", si.itemSize);
    Console.WriteLine("Unit Price: {0}", si.unitPrice);
    }
    }

    return 0;
    }
    }
  11. Execute the application to test it
  12. When requested, provide the data as follows:
     
    Item Number: 279475
    Item Name: Wool Jersey Ruffle Dress
    Size: 8
    Unit Price: 150
    Item Number: 729070
    Item Name: Mid-Weight Flat-Front Wool Trouser Pants
    Size: 36W - 30L
    Unit Price: 69.95
    Item Number: 297004
    Item Name: Ponte Pencil Skirt with Pleated Detail
    Size: 16
    Unit Price: 80
    Item Number: -1
    Department Store Inventory
    ------------------------
    Enter Item #: 279475
    Enter Item Name: Wool Jersey Ruffle Dress
    Enter Item Size: 8
    Enter Unit Price: 150
    =-= Store Item =-=
    Item #: 279475
    Item Name: Wool Jersey Ruffle Dress
    Size: 8
    Unit Price: 150
    ------------------------
    Enter Item #: 729070
    Enter Item Name: Mid-Weight Flat-Front Wool Trouser Pants
    Enter Item Size: 36W - 30L
    Enter Unit Price: 69.95
    =-= Store Item =-=
    Item #: 729070
    Item Name: Mid-Weight Flat-Front Wool Trouser Pants
    Size: 36W - 30L
    Unit Price: 69.95
    ------------------------
    Enter Item #: 297004
    Enter Item Name: Ponte Pencil Skirt With Pleated Detail
    Enter Item Size: 16
    Enter Unit Price: 80
    =-= Store Item =-=
    Item #: 297004
    Item Name: Ponte Pencil Skirt With Pleated Detail
    Size: 16
    Unit Price: 80
    ------------------------
    Enter Item #: -1
  13. Close the DOS window and return to your programming environment
Recursion

 
Introduction

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.

ApplicationApplication: Introducing Recursion

  1. To start a new application, on the main menu, click File -> New Project...
  2. In the middle list, click Empty Project
  3. Change the nema to Recursions and press Enter
  4. In the Solution Explorer, right-click Recursions -> Add -> New Item
  5. In the middle list, click Code File
  6. Change the name to Calculator and press Enter
Creating a Recursive Method

 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:
  • In its body, the method must call itself
  • Before or after calling itself, the method must check a condition that would allow it to stop, otherwise, it might run continuously
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 . . .
 
ApplicationApplication: Creating a Recursive Method

  1. To create a recursive function, change the document as follows:
    using System;

    public class Calculator
    {
    private long Factorial(long number)
    {
    if (number <= 1)
    return 1;
    return number * Factorial(number - 1);
    }

    public static int Main()
    {
    long factor = 0;
    Calculator exo = new Calculator();

    Console.Write("To calculate a factorial, enter a (small positive) number: ");
    factor = long.Parse(Console.ReadLine());

    Console.WriteLine("The factorial of {0} = {1}",
    factor, exo.Factorial(factor));

    System.Console.ReadKey();
    return 0;
    }
    }
  2. Execute the application to test it
  3. When asked to provide a number, type 8 and press Enter:
    To calculate a factorial, enter a (small positive) number: 8
    The factorial of 8 = 40320
    Press any key to continue . . .
  4. Press Enter to close the DOS window
Using Recursive Methods

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:
                1 = 1
            1 + 3 = 4
        1 + 3 + 5 = 9
    1 + 3 + 5 + 7 = 16
1 + 3 + 5 + 7 + 9 = 25
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 . . .
 
ApplicationApplication: Using Recursive Methods

  1. Change the document as follows:
    using System;

    public class Calculator
    {
    private long Factorial(long number)
    {
    if (number <= 1)
    return 1;
    return number * Factorial(number - 1);
    }

    private long Permutation(long n, long r)
    {
    if (r == 0)
    return 0;
    if (n == 0)
    return 0;
    if ((r >= 0) && (r <= n))
    return Factorial(n) / Factorial(n - r);
    else
    return 0;
    }

    private long Combinatorial(long a, long b)
    {
    if (a <= 1)
    return 1;

    return Factorial(a) / ((Factorial(b) * Factorial(a - b)));
    }

    public static int Main()
    {
    long factor = 0;
    long second = 0;
    Calculator exo = new Calculator();

    Console.Write("To calculate a factorial, enter a (small positive) number: ");
    factor = long.Parse(Console.ReadLine());
    Console.Write("To calculate a permutation and the combination, enter a second 
    (small positive) number: ");
    second = long.Parse(Console.ReadLine());

    Console.WriteLine("Factorial: F({0}) = {1}",
    factor, exo.Factorial(factor));
    Console.WriteLine("Permutation: P({0}, {1}) = {2}",
    factor, second, exo.Permutation(factor, second));
    Console.WriteLine("Combination: C({0}, {1}) = {2}",
    factor, second, exo.Combinatorial(factor, second));

    System.Console.ReadKey();
    return 0;
    }
    }
  2. Execute the application to test it
  3. When asked to provide a number, type 20 and press Enter
  4. When asked to provide a second number, type 5 and press Enter:
    To calculate a factorial, enter a (small positive) number: 20
    To calculate a permutation and the combination, enter a second (small positive)
    number: 5
    Factorial: F(20) = 2432902008176640000
    Permutation: P(20, 5) = 1860480
    Combination: C(20, 5) = 15504
  5. Press Enter to close the DOS window
  6. On the main menu, click File -> Close Solution
  7. When asked whether you want to save, click No

Counting and Looping

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.
 
ApplicationApplication: Introducing Conditional Looping

  1. Start Microsoft Visual Studio
  2. To create a new application, on the main menu, click File -> New Project...
  3. In the middle list, click Empty Project
  4. Change the Name to NationalBank4 and press Enter
  5. To create a new file, on the main menu, click Project -> Add New Item...
  6. In the middle list, click Code File
  7. Change the Name of the file to Customer
  8. Click Add
  9. 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;
    }
    }
  10. To create a new file, in the Solution Explorer, right-click NationalBank4 -> Add -> New Item...
  11. In the middle list, make sure Code File is selected.
    Change the Name to Management and press Enter
  12. 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:
While
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:
While
ApplicationApplication: Using while

  1. 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;
    }
    }
  2. Press F5 to execute
  3. 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
  4. Press Enter
  5. Press Enter to close the DOS window and return to your programming environment
do This while a Condition is True

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.
do...while
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 "}".

ApplicationApplication: Introducing Counting and Looping

  1. 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;
    }
    }
  2. Press F5 to execute
  3. 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
  4. 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:
  5. When asked what you want to do, type 2 to make a deposit and press Enter
  6. 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
    ===========================================
  7. Press Enter to close the DOS window and return top your programming environment
  8. Close your programming environment
Controlling the Conditional Statements

 
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 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 . . .
 
ApplicationApplication: Nesting Conditions

  1. 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;
    }
    }
  2. Press F5 to execute
  3. Enter information as follows:
     
    Account # 202-410443-240
    Account Type: 1
    Customer Name: Paul Martin Eloundou
    PIN: 8402
    Initial Deposit: 750
  4. 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:
  5. When asked to specify the next action, type 3 to withdraw money and press Enter
  6. 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:
  7. Type the next action as 2 and press Enter
  8. 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:
  9. Type the next action as 3 and press Enter
  10. 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.
  11. 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:
  12. Type 0 and press Enter
  13. Press Enter again to close the DOS window and return to your programming environment
Locking a Transaction

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
 
ApplicationApplication: Locking a Transaction

  1. 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;
    }
    }
  2. Press F5 to execute
  3. Follow the same steps of the previous section
  4. Return to your programming environment
Breaking the Flow of a Conditional Statement

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 . . .
 
Continuing a Conditional Statement

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.

Changing a Value in the Loop

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.

Going to a Designated Label

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 . . .
 
ApplicationApplication: Going to a Label

  1. 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;
    }
    }
  2. Press F5 to execute
  3. Enter information as follows:
     
    Account #: 202-103344-042
    Account Type: 2
    Customer Name: Jimmy Simms
    PIN: 2468
    Initial Deposit 500
  4. 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:
  5. When asked to specify the next action, type 2 to make a deposit and press Enter
  6. 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:
  7. For the next action, type 0 and press Enter
  8. Press Enter to close the DOS window and return to your programming environment
  9. Close your programming environment

Conditional Switches

Case Switches

 
Introduction

When defining an expression whose result would lead to a specific program execution, the switch statement considers that result and executes a statement based on the possible outcome of that expression, 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 syntax of the switch statement is:
switch(Expression)
{
case Choice1:
Statement1;
break;
case Choice2:
Statement2;
break;
case Choice-n:
Statement-n;
break;
}
 
In C++, you can omit the break keyword in a case. This creates the "fall through" effect as follows: after code executes in a case, if nothing "stops" it, the execution continues to the next case. This has caused problems and confusing execution in the past in some C++ programs. To avoid it, C# requires code interruption at the end of every case. This interruption is done using the break keyword.
The expression to examine in a case statement is an integer. Since a member of an enumerator (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 System;

public enum HouseType
{
Unknown,
SingleFamily,
Townhouse,
Condominium
}

public class Exercise
{
public static int Main()
{
var type = HouseType.Unknown;
var choice = 0;
var garage = "";

Console.WriteLine("Enter the type of house you want to purchase");
Console.WriteLine("1. Single Family");
Console.WriteLine("2. Townhouse");
Console.WriteLine("3. Condominium");
Console.Write("You Choice? ");
choice = int.Parse(Console.ReadLine());

switch (choice)
{
case 1:
type = HouseType.SingleFamily;
break;

case 2:
type = HouseType.Townhouse;
break;

case 3:
type = HouseType.Condominium;
break;
}


Console.Write("Does the house have an indoor garage (1=Yes/0=No)? ");
var answer = int.Parse(Console.ReadLine());
if (answer == 1)
garage = "Yes";
else
garage = "No";

Console.WriteLine("\nDesired House Type: {0}", type);
Console.WriteLine("Has indoor garage? {0}", garage);

return 0;
}
}
When establishing the possible outcomes that the switch statement should consider, at times there will be 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 syntax of the switch statement that considers the default case would be:
switch(Expression)
{
case Choice1:
Statement1;
break;
case Choice2:
Statement2;
break;
case Choice-n:
Statement-n;
break;
default:
Other-Possibility;
break;
}
In C++, the default section doesn't need a break keyword because it is the last. In C#, every case and the default section must have its own exit mechanism, which is taken care of by a break keyword.
Therefore another version of the program above would be
using System;

public enum HouseType
{
Unknown,
SingleFamily,
Townhouse,
Condominium
}

public class Exercise
{
public static int Main()
{
var type = HouseType.Unknown;
var choice = 0;
var garage = "";

Console.WriteLine("Enter the type of house you want to purchase");
Console.WriteLine("1. Single Family");
Console.WriteLine("2. Townhouse");
Console.WriteLine("3. Condominium");
Console.Write("You Choice? ");
choice = int.Parse(Console.ReadLine());

switch (choice)
{
case 1:
type = HouseType.SingleFamily;
break;

case 2:
type = HouseType.Townhouse;
break;

case 3:
type = HouseType.Condominium;
break;

default:
type = HouseType.Unknown;
break;

}

Console.Write("Does the house have an indoor garage (1=Yes/0=No)? ");
var answer = int.Parse(Console.ReadLine());
if (answer == 1)
garage = "Yes";
else
garage = "No";

Console.WriteLine("\nDesired House Type: {0}", type);
Console.WriteLine("Has indoor garage? {0}", garage);

return 0;
}
}
Here is an example of running the program:
Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 8
Does the house have an indoor garage (1=Yes/0=No)? 2

Desired House Type: Unknown
Has indoor garage? No
Press any key to continue . . .
Besides a value of an int type, you can also use another variant of integers on a switch statement. For example, you can use letters to validate the cases. Here is an example:
using System;

public enum HouseType
{
Unknown,
SingleFamily,
Townhouse,
Condominium
}

public class Exercise
{
public static int Main()
{
var type = HouseType.Unknown;
var choice = 0;
var garage = "";

Console.WriteLine("Enter the type of house you want to purchase");
Console.WriteLine("1. Single Family");
Console.WriteLine("2. Townhouse");
Console.WriteLine("3. Condominium");
Console.Write("You Choice? ");
choice = int.Parse(Console.ReadLine());

switch (choice)
{
case 1:
type = HouseType.SingleFamily;
break;

case 2:
type = HouseType.Townhouse;
break;

case 3:
type = HouseType.Condominium;
break;

default:
type = HouseType.Unknown;
break;
}

Console.Write("Does the house have an indoor garage (y/n)? ");
var answer = char.Parse(Console.ReadLine());

switch (Answer)
{
case 'y':
garage = "Yes";
break;

case 'Y':
garage = "Yes";
break;

case 'n':
garage = "No";
break;

case 'N':
garage = "No";
break;

default:
garage = "Not Specified";
break;
}


Console.WriteLine("\nDesired House Type: {0}", type);
Console.WriteLine("Has indoor garage? {0}", garage);

return 0;
}
}
Here is an example of running the program:
Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 3
Does the house have an indoor garage (y/n)? y

Desired House Type: Condominium
Has indoor garage? Yes
Press any key to continue . . .
 
ApplicationApplication: Introducing Conditional Switches

  1. Start Microsoft Visual Studio
  2. To create a new application, on the main menu, click File -> New Project...
  3. In the middle list, click Empty Project
  4. Change the Name to NationalBank3 and press Enter
  5. To create a new file, on the main menu, click Project -> Add New Item...
  6. In the middle list, click Code File
  7. Change the Name of the file to Customer
  8. Click Add
  9. 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;
    }
    }
  10. To create a new file, in the Solution Explorer, right-click NationalBank3 -> Add -> New Item...
  11. In the middle list, make sure Code File is selected.
    Change the Name to Management and press Enter
  12. 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()
    {
    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);

    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());

    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;
    }

    Console.Clear();
    registration.ShowAccountInformation(accountHolder);

    Console.ReadKey();
    return 0;
    }
    }
  13. Press F5 to execute
  14. Enter information as follows:
     
    Account # 202-410443-240
    Account Type: 1
    Customer Name: Paul Martin Eloundou
    PIN: 8402
    Initial Deposit: 750
    ===========================================
    ==-= National Bank =-======================
    -------------------------------------------
    Enter a number for the new account(000-000000-000)202-410443-240
    What type of account the customer wants to open
    1 - Checking Account
    2 - Savings Account
    Enter account type: 1
    Enter customer name: Paul Martin Eloundou
    Ask the customer to enter a PIN: 8402
    Enter the customer's initial deposit
    Amount: 750
  15. 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
  16. When asked for the next action, type 2 and press Enter
  17. Type the amount as 226.85 and press Enter
  18. Press Enter to close the DOS window and return to your programming environment
Combining Cases

Each of the cases we have used so far examined only one possibility before executing the corresponding statement. You can combine cases to execute the same statement. To do this, type a case, its value, and the semi-colon. Type another case using the same formula. When the cases are ready, you can then execute the desired statement. Here is an example:
using System;

public enum HouseType
{
Unknown,
SingleFamily,
Townhouse,
Condominium
}

public class Exercise
{
public static int Main()
{
var type = HouseType.Unknown;
var choice = 0;
var garage = "";

Console.WriteLine("Enter the type of house you want to purchase");
Console.WriteLine("1. Single Family");
Console.WriteLine("2. Townhouse");
Console.WriteLine("3. Condominium");
Console.Write("You Choice? ");
choice = int.Parse(Console.ReadLine());

switch (choice)
{
case 1:
type = HouseType.SingleFamily;
break;

case 2:
type = HouseType.Townhouse;
break;

case 3:
type = HouseType.Condominium;
break;

default:
type = HouseType.Unknown;
break;
}

Console.Write("Does the house have an indoor garage (y/n)? ");
var answer = char.Parse(Console.ReadLine());
switch (answer)
{
case 'y':
case 'Y':

garage = "Yes";
break;

case 'n':
case 'N':

garage = "No";
break;

default:
garage = "Not Specified";
break;
}

Console.WriteLine("\nDesired House Type: {0}", type);
Console.WriteLine("Has indoor garage? {0}", garage);

return 0;
}
}
This would produce:
Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 3
Does the house have an indoor garage (y/n)? Y

Desired House Type: Condominium
Has indoor garage? Yes
Press any key to continue . . .
 
Using Enumerations

One of the most fundamental uses of enumerations is to process them in a switch statement. To do this, you pass the value of an enumeration to a switch. The values of the enumerations are then processed in the case statements. Here is an example:
using System;

public enum HouseType
{
Unknown,
SingleFamily,
Townhouse,
Condominium
}

public class Exercise
{
public static int Main()
{
var PropertyType = "";
var choice = 0;
var garage = "";

Console.WriteLine("Enter the type of house you want to purchase");
Console.WriteLine("1. Single Family");
Console.WriteLine("2. Townhouse");
Console.WriteLine("3. Condominium");
Console.Write("You Choice? ");
choice = int.Parse(Console.ReadLine());

switch ((HouseType)choice)
{
case HouseType.SingleFamily:
PropertyType = "Single Family";
break;

case HouseType.Townhouse:
PropertyType = "Townhouse";
break;

case HouseType.Condominium:
PropertyType = "Condominium";
break;

default:
PropertyType = "Unknown";
break;
}


Console.Write("Does the house have an indoor garage (y/n)? ");
var answer = char.Parse(Console.ReadLine());

switch (answer)
{
case 'y':
case 'Y':
garage = "Yes";
break;

case 'n':
case 'N':
garage = "No";
break;

default:
garage = "Not Specified";
break;
}

Console.WriteLine("\nDesired House Type: {0}", PropertyType);
Console.WriteLine("Has indoor garage? {0}", garage);

return 0;
}
}
Here is an example of running the program:
Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 1
Does the house have an indoor garage (y/n)? N

Desired House Type: Single Family
Has indoor garage? No
Press any key to continue . . .
 
Logical Conjunction: AND

 
Introduction

Imagine that a real estate agent who will be using your program is meeting with a potential buyer and asking questions from the following program:
using System;

public enum HouseType
{
Unknown,
SingleFamily,
Townhouse,
Condominium
}

public class Program
{
static int Main()
{
var type = HouseType.Unknown;
var choice = 0;
var value = 0D;

Console.WriteLine("Enter the type of house you want to purchase");
Console.WriteLine("1. Single Family");
Console.WriteLine("2. Townhouse");
Console.WriteLine("3. Condominium");
Console.Write("You Choice? ");
choice = int.Parse(Console.ReadLine());

if (choice == 1)
type = HouseType.SingleFamily;
if (choice == 2)
type = HouseType.Townhouse;
if (choice == 3)
type = HouseType.Condominium;

Console.Write("Up to how much can you afford? $");
value = double.Parse(Console.ReadLine());

Console.WriteLine("\nDesired House Type: {0}", type);
Console.WriteLine("Maximum value afforded: {0:C}\n", value);

return 0;
}
}
Suppose a customer responds to these questions: she indicates that she wants single family house but she cannot afford more than $550,000:
Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 1
Up to how much can you afford? $550000

Desired House Type: SingleFamily
Maximum value afforded: $550,000.00

Press any key to continue . . .
When considering a house for this customer, there are two details to be validated here: the house must be a single family home, second, it must cost less than $550,001. We can create two statements as follows:
  1. The house is single family
  2. The house costs less than $550,000
From our list of real estate properties, if we find a house that is a single family home, we put it in our list of considered properties:
Type of House House
The house is single family True
On the other hand, if we find a house that is less than or equal to $550,000, we retain it:
Price Range Value
$550,000 True
One of the ways you can combine two comparisons is by joining them. For our customer, we want a house to meet BOTH criteria. If the house is a town house, based on the request of our customer, its conditional value is false. If the house is more than $550,000, the value of the Boolean Value is true. The Boolean operator used to join two criteria is called AND. This can be illustrated as follows:
Type of House House Value Result
Town House $625,000 Town House AND $625,000
False False False
In C#, the Boolean AND operator is performed using the && operator. Here is an example:
using System;

public enum HouseType
{
Unknown,
SingleFamily,
Townhouse,
Condominium
}

public class Exercise
{
static int Main()
{
var type = HouseType.Unknown;
var choice = 0;
var value = 0D;

Console.WriteLine("Enter the type of house you want to purchase");
Console.WriteLine("1. Single Family");
Console.WriteLine("2. Townhouse");
Console.WriteLine("3. Condominium");
Console.Write("You Choice? ");
choice = int.Parse(Console.ReadLine());

Console.Write("Up to how much can you afford? $");
value = double.Parse(Console.ReadLine());

if(choice == 1)
type = HouseType.SingleFamily;
if (choice == 2)
type = HouseType.Townhouse;
if (choice == 3)
type = HouseType.Condominium;
Console.WriteLine("\nDesired House Type: {0}", type);
Console.WriteLine("Maximum value afforded: {0:C}", value);

if (type == HouseType.SingleFamily && value <= 550000)
Console.WriteLine("\nDesired House Matched");
return 0;
}
}
Here is an example of running the program:
Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 1
Up to how much can you afford? $450000

Desired House Type: SingleFamily
Maximum value afforded: $450,000.00

Desired House Matched
Press any key to continue . . .
By definition, a logical conjunction combines two conditions. To make the program easier to read, each side of the conditions can be included in parentheses. Here is an example:
using System;

public enum HouseType
{
Unknown,
SingleFamily,
Townhouse,
Condominium
}

public class Exercise
{
static int Main()
{
var type = HouseType.Unknown;
var choice = 0;
var value = 0D;

. . .

if( (type == HouseType.SingleFamily) && (value <= 550000) )
Console.WriteLine("\nDesired House Matched");
return 0;
}
}
Suppose we find a single family home. The first condition is true for our customer. With the AND Boolean operator, if the first condition is true, then we consider the second criterion. Suppose that the house we are considering costs $750,500: the price is out of the customer's range. Therefore, the second condition is false. In the AND Boolean algebra, if the second condition is false, even if the first is true, the whole condition is false. This would produce the following table:
Type of House House Value Result
Single Family $750,500 Single Family AND $750,500
True False False
This can be illustrated by the following run of the program:
using System;

public enum HouseType
{
Unknown,
SingleFamily,
Townhouse,
Condominium
}

class Program
{
static void Main()
{
var type = HouseType.Unknown;
int choice;
var value = 0M;

Console.WriteLine("Enter the type of house you want to purchase");
Console.WriteLine("1. Single Family");
Console.WriteLine("2. Townhouse");
Console.WriteLine("3. Condominium");
Console.Write("You Choice? ");
choice = int.Parse(Console.ReadLine());

if (choice == 1)
type = HouseType.SingleFamily;
if (choice == 2)
type = HouseType.Townhouse;
if (choice == 3)
type = HouseType.Condominium;

Console.Write("Up to how much can you afford? $");
value = decimal.Parse(Console.ReadLine());

Console.WriteLine("\nDesired House Type: {0}", type);
Console.WriteLine("Maximum value afforded: {0:C}", value);

if (type == HouseType.SingleFamily && value <= 550000)
Console.WriteLine("\nDesired House Matched");
else
Console.WriteLine("\nThe House Doesn't Match the Desired Criteria");

}
}
Here is an example of running the program:
Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 1
Up to how much can you afford? $750000

Desired House Type: SingleFamily
Maximum value afforded: $750,000.00

The House Doesn't Match the Desired Criteria
Press any key to continue . . .
Suppose we find a townhouse that costs $420,000. Although the second condition is true, the first is false. In Boolean algebra, an AND operation is false if either condition is false:
Type of House House Value Result
Town House $420,000 Town House AND $420,000
False True False
Here is an example of running the above program:
Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 2
Up to how much can you afford? $420000

Desired House Type: Townhouse
Maximum value afforded: $420,000.00

The House Doesn't Match the Desired Criteria

Press any key to continue . . .
If we find a single family home that costs $345,000, both conditions are true. In Boolean algebra, an AND operation is true if BOTH conditions are true. This can be illustrated as follows:
Type of House House Value Result
Single Family $345,000 Single Family AND $345,000
True True True
This can be revealed in the following run of the above program:
Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 1
Up to how much can you afford? $345000

Desired House Type: SingleFamily
Maximum value afforded: $345,000.00

Desired House Matched

Press any key to continue . . .
These four tables can be resumed as follows:
If Condition1 is If Condition2 is Condition1
AND
Condition2
False False False
False True False
True False False
True True True
As you can see, a logical conjunction is true only of BOTH conditions are true.

Combining Conjunctions

As seen above, the logical conjunction operator is used to combine two conditions. In some cases, you will need to combine more than two conditions. Imagine a customer wants to purchase a single family house that costs up to $450,000 with an indoor garage. This means that the house must fulfill these three requirements:
  1. The house is a single family home
  2. The house costs less than $450,001
  3. The house has an indoor garage
Here the program that could be used to check these conditions:
using System;

public enum HouseType
{
Unknown,
SingleFamily,
Townhouse,
Condominium
}

public class Exercise
{
static int Main()
{
var type = HouseType.Unknown;
var choice = 0;
var value = 0D;
var hasIndoorGarage = false;

Console.WriteLine("Enter the type of house you want to purchase");
Console.WriteLine("1. Single Family");
Console.WriteLine("2. Townhouse");
Console.WriteLine("3. Condominium");
Console.Write("You Choice? ");
choice = int.Parse(Console.ReadLine());

if (choice == 1)
type = HouseType.SingleFamily;
if (choice == 2)
type = HouseType.Townhouse;
if (choice == 3)
type = HouseType.Condominium;

Console.Write("Up to how much can you afford? $");
value = double.Parse(Console.ReadLine());

Console.Write("Does the house have an indoor garage (1=Yes/0=No)? ");
int ans = int.Parse(Console.ReadLine());

Console.WriteLine("\nDesired House Type: {0}", type);
Console.WriteLine("Maximum value afforded: {0:C}", value);
Console.Write("House has indoor garage: ");
if (ans == 1)
Console.WriteLine("Yes");
else
Console.WriteLine("No");

if ((type == HouseType.SingleFamily) && (value <= 550000) && (ans == 1))
Console.WriteLine("\nDesired House Matched");
else
Console.WriteLine("\nThe House Doesn't Match the Desired Criteria");


return 0;
}
}
We saw that when two conditions are combined, the compiler first checks the first condition, followed by the second. In the same way, if three conditions need to be considered, the compiler evaluates the truthfulness of the first condition:
Type of House
A
Town House
False
If the first condition (or any condition) is false, the whole condition is false, regardless of the outcome of the other(s). If the first condition is true, then the second condition is evaluated for its truthfulness:
Type of House Property Value
A B
Single Family $655,000
True False
If the second condition is false, the whole combination is considered false:
A B A && B
True False False
When evaluating three conditions, if either the first or the second is false, since the whole condition would become false, there is no reason to evaluate the third. If both the first and the second conditions are false, there is also no reason to evaluate the third condition. Only if the first two conditions are true will the third condition be evaluated whether it is true:
Type of House Property Value Indoor Garage
A B C
Single Family $425,650 None
True True False
The combination of these conditions in a logical conjunction can be written as A && B && C. If the third condition is false, the whole combination is considered false:
A B A && B C A && B && C
True True True False False
To verify this, here is an example of running the program:
Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 1
Up to how much can you afford? $425000
Does the house have an indoor garage (1=Yes/0=No)? 0

Desired House Type: SingleFamily
Maximum value afforded: $425,000.00
House has indoor garage: No

The House Doesn't Match the Desired Criteria

Press any key to continue . . .
From our discussion so far, the truth table of the combinations can be illustrated as follows:
A B C A && B && C
False Don't Care Don't Care False
True False Don't Care False
True True False False
The whole combination is true only if all three conditions are true. This can be illustrated as follows:
A B C A && B && C
False False False False
False False True False
True False False False
True False True False
False True False False
False True True False
True True False False
True True True True
 
Logical Disjunction: OR

 
Introduction

Our real estate company has single family homes, townhouses, and condominiums. All of the condos have only one level, also referred to as a story. Some of the single family homes have one story, some have two and some others have three levels. All townhouses have three levels.

Another customer wants to buy a home. The customer says that he primarily wants a condo, but if our real estate company doesn't have a condominium, that is, if the company has only houses, whatever it is, whether a house or a condo, it must have only one level (story) (due to an illness, the customer would not climb the stairs). When considering the properties of our company, we would proceed with these statements:
  1. The property is a condominium
  2. The property has one story
If we find a condo, since all of our condos have only one level, the criterion set by the customer is true. Even if we were considering another (type of) property, it wouldn't matter. This can be resumed in the following table:
Type of House House
Condominium True
The other properties would not be considered, especially if they have more than one story:
Number of Stories Value
3 False
To check for either of two conditions, in Boolean algebra, you can use an operator called OR. We can show this operation as follows:
Condominium One Story Condominium OR 1 Story
True False True
In Boolean algebra, this type of comparison is performed using the OR operator. In C#, the OR operator is performed using the || operator. Here is an example:
using System;

public enum HouseType
{
Unknown,
SingleFamily,
Townhouse,
Condominium
}

public class Exercise
{
static int Main()
{
var type = HouseType.Unknown;
var choice = 0;
var stories = 1;

Console.WriteLine("Enter the type of house you want to purchase");
Console.WriteLine("1. Single Family");
Console.WriteLine("2. Townhouse");
Console.WriteLine("3. Condominium");
Console.Write("You Choice? ");
choice = int.Parse(Console.ReadLine());

if (choice == 1)
type = HouseType.SingleFamily;
if (choice == 2)
type = HouseType.Townhouse;
if (choice == 3)
type = HouseType.Condominium;

Console.Write("How many stories? ");
stories = int.Parse(Console.ReadLine());

Console.WriteLine("\nDesired House Type: {0}", type);
Console.WriteLine("Number of Stories: {0}", stories);

if ((type == HouseType.Condominium) || (stories == 1))
Console.WriteLine("\nDesired House Matched");
else
Console.WriteLine("\nThe House Doesn't Match the Desired Criteria");

return 0;
}
}
Here is an example of running the program:
Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 3
How many stories? 6

Desired House Type: Condominium
Number of Stories: 6

Desired House Matched

Press any key to continue . . .
Suppose that, among the properties our real estate company has available, there is no condominium. In this case, we would then consider the other properties:
Type of House House
Single Family False
If we have a few single family homes, we would look for one that has only one story. Once we find one, our second criterion becomes true:
Type of House One Story Condominium OR 1 Story
False True True
This can be illustrated in the following run of the above program:
Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 1
How many stories? 1

Desired House Type: SingleFamily
Number of Stories: 1

Desired House Matched

Press any key to continue . . .
If we find a condo and it is one story, both criteria are true. This can be illustrated in the following table:
Type of House One Story Condominium OR 1 Story
False True True
True True True
The following run of the program demonstrates this:
Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 3
How many stories? 1

Desired House Type: Condominium
Number of Stories: 1

Desired House Matched
Press any key to continue . . .
A Boolean OR operation produces a false result only if BOTH conditions ARE FALSE:
If Condition1 is If Condition2 is Condition1 OR Condition2
False True True
True False True
True True True
False False False
Here is another example of running the program:
Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 2
How many stories? 2

Desired House Type: Townhouse
Number of Stories: 2

The House Doesn't Match the Desired Criteria
Press any key to continue . . .
 
Combinations of Disjunctions

As opposed to evaluating only two conditions, you may face a situation that presents three of them and must consider a combination of more than two conditions.

ApplicationApplication: Ending the Lesson

  1. Close your programming environment
  2. When asked whether you want to save, click No