Introduction to Conditional Conjunctions

Overview

In previous lessons, all the conditions we studied were dealing with one issue. Sometimes, you want to combine two or more conditions that address a common issue.

Practical LearningPractical Learning: Introducing Conditional Conjunctions

  1. Start Microsoft Visual Studio. On the Visual Studio 2022 dialog box, click Create a New Project
  2. Make sure Console App is selected.
    Click Next
  3. Change the project Name to TaxPreparation02. Accept or change the project Location and press Enter
  4. Make sure the Framework combo box is displaying .NET 6.0 (Long-Term Support) and press Enter
  5. Change the document as follows:
    using static System.Console;
    
    WriteLine("========================================================");
    WriteLine(" - Georgia - State Income Tax -");
    WriteLine("========================================================");
            
    double addedAmount;
    double taxRate;
            
    WriteLine("Enter the information for tax preparation");
    Write("Gross Salary:  ");
    double grossSalary = double.Parse(ReadLine());
            
    // Georgia
    string filingStatus = "Married Filing Joint or Head of Household";
       
    if(grossSalary is >= 10_000)
    {
        addedAmount = 340;
        taxRate     = 5.75;
    }
    else if(grossSalary is >= 7_000)
    {
        addedAmount = 190;
        taxRate     = 5.00;
    }
    else if(grossSalary is >= 5_000)
    {
        addedAmount = 110;
        taxRate     = 4.00;
    }
    else if(grossSalary is >= 3_000)
    {
        addedAmount = 50;
        taxRate     = 3.00;
    }
    else if(grossSalary is >= 1_000)
    {
        addedAmount = 10;
        taxRate     = 2.00;
    }
    else // if grossSalary < 1_000:)
    {
        addedAmount = 0;
        taxRate     = 1.00;
    }
            
    double taxAmount = addedAmount + (grossSalary * taxRate / 100.00);
    double net_pay = grossSalary - taxAmount;
        
    WriteLine("========================================================");
    WriteLine("- Georgia - State Income Tax -");
    WriteLine("--------------------------------------------------------");
    WriteLine($"Gross Salary:  {grossSalary:f}");
    WriteLine($"Filing Status: {filingStatus}");
    WriteLine($"Tax Rate:      {taxRate:f}%");
    WriteLine($"Tax Amount:    {taxAmount:f}");
    WriteLine($"Net Pay:       {net_pay:f}");
    WriteLine("========================================================");
  6. To execute, on the main menu, click Debug -> Start Without Debugging
  7. For the Gross Salary, type 999.99 and press Enter
    ========================================================
     - Georgia - State Income Tax -
    ========================================================
    Enter the information for tax preparation
    Gross Salary:  999.99
    ========================================================
    - Georgia - State Income Tax -
    --------------------------------------------------------
    Gross Salary:  999.99
    Filing Status: Married Filing Joint or Head of Household
    Tax Rate:      1.00%
    Tax Amount:    10.00
    Net Pay:       989.99
    ========================================================
    Press any key to close this window . . .
  8. Press Enter to close the window and return to your programming environment
  9. To execute again, on the main menu, click Debug -> Start Without Debugging
  10. For the Gross Salary, type 1000 and press Enter
    ========================================================
     - Georgia - State Income Tax -
    ========================================================
    Enter the information for tax preparation
    Gross Salary:  1000
    ========================================================
    - Georgia - State Income Tax -
    --------------------------------------------------------
    Gross Salary:  1000.00
    Filing Status: Married Filing Joint or Head of Household
    Tax Rate:      2.00%
    Tax Amount:    30.00
    Net Pay:       970.00
    ========================================================
    Press any key to close this window . . .
  11. Press Enter to close the window and return to your programming environment
  12. To execute again, on the main menu, click Debug -> Start Without Debugging
  13. For the Gross Salary, type 5726.87 and press Enter
    ========================================================
     - Georgia - State Income Tax -
    ========================================================
    Enter the information for tax preparation
    Gross Salary:  5726.87
    ========================================================
    - Georgia - State Income Tax -
    --------------------------------------------------------
    Gross Salary:  5726.87
    Filing Status: Married Filing Joint or Head of Household
    Tax Rate:      4.00%
    Tax Amount:    339.07
    Net Pay:       5387.80
    ========================================================
    Press any key to close this window . . .
  14. Press Enter to close the window and return to your programming environment
  15. Change the document as follows:
    using static System.Console;
    
    WriteLine("========================================================");
    WriteLine(" - Georgia - State Income Tax -");
    WriteLine("========================================================");
            
    double addedAmount;
    double taxRate;
            
    WriteLine("Enter the information for tax preparation");
    Write("Gross Salary:  ");
    double grossSalary = double.Parse(ReadLine());
            
    //Georgia
    string filingStatus = "Single";
       
    if( grossSalary is >= 7_000)
    {
        addedAmount = 230;
        taxRate     = 5.75;
    }
    else if(grossSalary is >= 5_250)
    {
        addedAmount = 143;
        taxRate     = 5.00;
    }
    else if(grossSalary is >= 3_750)
    {
        addedAmount = 83;
        taxRate     = 4.00;
    }
    else if(grossSalary is >= 2_250)
    {
        addedAmount = 38;
        taxRate     = 3.00;
    }
    else if(grossSalary is >= 750)
    {
        addedAmount = 8;
        taxRate     = 2.00;
    }
    else // if grossSalary < 750:)
    {
        addedAmount = 0;
        taxRate     = 1.00;
    }
            
    double taxAmount = addedAmount + (grossSalary * taxRate / 100.00);
    double net_pay = grossSalary - taxAmount;
        
    WriteLine("========================================================");
    WriteLine("- Georgia - State Income Tax -");
    WriteLine("--------------------------------------------------------");
    WriteLine($"Gross Salary:  {grossSalary:f}");
    WriteLine($"Filing Status: {filingStatus}");
    WriteLine($"Tax Rate:      {taxRate:f}%");
    WriteLine($"Tax Amount:    {taxAmount:f}");
    WriteLine($"Net Pay:       {net_pay:f}");
    WriteLine("========================================================");
  16. To execute the application and test it, on the main menu, click Debug -> Start Without Debugging
  17. For the Dross Salary, type 749.99 and press Enter
    ========================================================
     - Georgia - State Income Tax -
    ========================================================
    Enter the information for tax preparation
    Gross Salary:  749.99
    ========================================================
    - Georgia - State Income Tax -
    --------------------------------------------------------
    Gross Salary:  749.99
    Filing Status: Single
    Tax Rate:      1.00%
    Tax Amount:    7.50
    Net Pay:       742.49
    ========================================================
    Press any key to close this window . . .
  18. Press C to close the window and return to your programming environment
  19. To execute the application and test it again, on the main menu, click Debug -> Start Without Debugging
  20. In the Terminal, click on the right side of Counter Reading Start, type 750 and press Enter
    ========================================================
     - Georgia - State Income Tax -
    ========================================================
    Enter the information for tax preparation
    Gross Salary:  750
    ========================================================
    - Georgia - State Income Tax -
    --------------------------------------------------------
    Gross Salary:  750.00
    Filing Status: Single
    Tax Rate:      2.00%
    Tax Amount:    23.00
    Net Pay:       727.00
    ========================================================
    Press any key to close this window . . .
  21. Press R to close the window and return to your programming environment
  22. To execute the application and test it again, on the main menu, click Run -> Run Without Debugging
  23. In the Terminal, click on the right side of Counter Reading Start, type 5726.87 and press Enter
    ========================================================
     - Georgia - State Income Tax -
    ========================================================
    Enter the information for tax preparation
    Gross Salary:  5726.87
    ========================================================
    - Georgia - State Income Tax -
    --------------------------------------------------------
    Gross Salary:  5726.87
    Filing Status: Single
    Tax Rate:      5.00%
    Tax Amount:    429.34
    Net Pay:       5297.53
    ========================================================
    Press any key to close this window . . .

Nesting a Conditional Statement

A conditional statement has a body, which is from where the condition is defined to where its behavior ends. In the body of the conditional statement, you can create another conditional statement. This is referred to as nesting the condition. The condition nesting can be formulated as follows:

if( condition1 )     // The nesting, main, parent, first, or external condition
    if( condition2 ) // The nested, child, second, or internal condition
    	statement(s)

If the code of a condition involves many lines of code, you can delimite its body with curly brackets:

if( condition1 )
{    
    if( condition2 )
    {
        statement(s)
    }
}

In the same way, you can nest one conditional statement in one, then nest that new one in another conditional statement, and so on. This can be formulated as follows:

if( condition1 )
    if( condition2 )
if( condition3 )
            statement(s)

If a section of code is long, you can include its child code in curly brackets:

if( condition1 )
{    
    if( condition2 )
    {    
        if( condition3 )
	{
            statement(s)
        }
    }
}

Practical LearningPractical Learning: Nesting a Conditional Statement

  1. Change the document as folloes:
    using static System.Console;
    
    WriteLine("========================================================");
    WriteLine(" - Georgia - State Income Tax -");
    WriteLine("========================================================");
    
    string filingStatus;
    double taxRate, addedAmount;
    
    WriteLine("Enter the information for tax preparation");
    Write("Gross Salary:  ");
    double grossSalary = double.Parse(ReadLine());
    WriteLine("Filing Status");
    WriteLine("s - Single");
    WriteLine("c - Married Filing Joint or Head of Household");
    Write("Enter Filing Status: ");
    string answer = ReadLine();
    
    if (answer == "s")
    {
        filingStatus = "Single";
    
        if (grossSalary is >= 7_000)
        {
            addedAmount = 230;
            taxRate     = 5.75;
        }
        else if (grossSalary is >= 5_250)
        {
            addedAmount = 143;
            taxRate     = 5.00;
        }
        else if (grossSalary is >= 3_750)
        {
            addedAmount = 83;
            taxRate     = 4.00;
        }
        else if (grossSalary is >= 2_250)
        {
            addedAmount = 38;
            taxRate     = 3.00;
        }
        else if (grossSalary is >= 750)
        {
            addedAmount = 8;
            taxRate     = 2.00;
        }
        else // if grossSalary < 750:)
        {
            addedAmount = 0;
            taxRate     = 1.00;
        }
    }
    else
    {
        filingStatus = "Married Filing Joint or Head of Household";
    
        if (grossSalary is >= 10_000)
        {
            addedAmount = 340;
            taxRate     = 5.75;
        }
        else if (grossSalary is >= 7_000)
        {
            addedAmount = 190;
            taxRate     = 5.00;
        }
        else if (grossSalary is >= 5_000)
        {
            addedAmount = 110;
            taxRate     = 4.00;
        }
        else if (grossSalary is >= 3_000)
        {
            addedAmount = 50;
            taxRate     = 3.00;
        }
        else if (grossSalary is >= 1_000)
        {
            addedAmount = 10;
            taxRate     = 2.00;
        }
        else // if grossSalary < 1_000:)
         {
            addedAmount = 0;
            taxRate     = 1.00;
        }
    }
    
    double taxAmount = addedAmount + (grossSalary * taxRate / 100.00);
    double net_pay = grossSalary - taxAmount;
    
    WriteLine("========================================================");
    WriteLine("- Georgia - State Income Tax -");
    WriteLine("--------------------------------------------------------");
    WriteLine($"Gross Salary:  {grossSalary:f}");
    WriteLine($"Filing Status: {filingStatus}");
    WriteLine($"Tax Rate:      {taxRate:f}%");
    WriteLine($"Tax Amount:    {taxAmount:f}");
    WriteLine($"Net Pay:       {net_pay:f}");
    WriteLine("========================================================");
  2. To execute, on the main menu, click Debug -> Start Without Debudding
  3. For the Gross Salary, type 5368.47 and press Enter
  4. For the Filing Statues, type s and press Enter:
    ========================================================
     - Georgia - State Income Tax -
    ========================================================
    Enter the information for tax preparation
    Gross Salary:  5368.47
    Filing Status
    s - Single
    c - Married Filing Joint or Head of Household
    Enter Filing Status: s
    ========================================================
    - Georgia - State Income Tax -
    --------------------------------------------------------
    Gross Salary:  5368.47
    Filing Status: Single
    Tax Rate:      5.00%
    Tax Amount:    411.42
    Net Pay:       4957.05
    ========================================================
    Press any key to close this window . . .
  5. Press R to close the window and return to your programming environment
  6. To execute again, on the main menu, click Debug -> Start Without Debudding
  7. For the Gross Salary, type 5368.47 and press Enter
  8. For the Filing Statues, type c and press Enter:
    ========================================================
     - Georgia - State Income Tax -
    ========================================================
    Enter the information for tax preparation
    Gross Salary:  5368.47
    Filing Status
    s - Single
    c - Married Filing Joint or Head of Household
    Enter Filing Status: c
    ========================================================
    - Georgia - State Income Tax -
    --------------------------------------------------------
    Gross Salary:  5368.47
    Filing Status: Married Filing Joint or Head of Household
    Tax Rate:      4.00%
    Tax Amount:    324.74
    Net Pay:       5043.73
    ========================================================
    Press any key to close this window . . .
  9. Press F to close the window and return to your programming environment
  10. To expand on nesting conditional statements, change the document as follows:
    using static System.Console;
    
    WriteLine("========================================================");
    WriteLine(" - Georgia - State Income Tax -");
    WriteLine("========================================================");
    
    string filingStatus;
    double taxRate, addedAmount;
    
    WriteLine("Enter the information for tax preparation");
    Write("Gross Salary:  ");
    double grossSalary = double.Parse(ReadLine());
    WriteLine("Filing Status");
    WriteLine("1 - Single");
    WriteLine("s - Married Filing Separate");
    WriteLine("j - Married Filing Joint or Head of Household");
    Write("Enter Filing Status: ");
    string answer = ReadLine();
    
    //Georgia
    if(answer == "j")
    {
        filingStatus = "Married Filing Joint or Head of Household";
    
        if (grossSalary is >= 10_000)
        {
            addedAmount = 340;
            taxRate     = 5.75;
        }
        else if (grossSalary is >= 7_000)
        {
            addedAmount = 190;
            taxRate     = 5.00;
        }
        else if (grossSalary is >= 5_000)
        {
            addedAmount = 110;
            taxRate     = 4.00;
        }
        else if (grossSalary is >= 3_000)
        {
            addedAmount = 50;
            taxRate     = 3.00;
        }
        else if (grossSalary is >= 1_000)
        {
            addedAmount = 10;
            taxRate     = 2.00;
        }
        else // if grossSalary < 1_000:)
        {
            addedAmount = 0;
            taxRate     = 1.00;
        }
    }
    else if (answer == "s")
    {
        filingStatus = "Married Filing Separate";
                
        if(grossSalary is >= 5_000)
        {
            addedAmount = 170;
            taxRate     = 5.75;
        }
        else if(grossSalary is >= 3_500)
        {
            addedAmount = 95;
            taxRate     = 5.00;
        }
        else if(grossSalary is >= 2_500)
        {
            addedAmount = 55;
            taxRate     = 4.00;
        }
        else if(grossSalary is >= 1_500)
        {
            addedAmount = 25;
            taxRate     = 3.00;
        }
        else if(grossSalary is >= 500)
        {
            addedAmount = 5;
            taxRate = 2.00;
        }
        else // if( grossSalary < 1_000)
        {
            addedAmount = 0;
            taxRate     = 1.00;
        }
    }
    else // if(answer == Anything)
    {
        filingStatus = "Single";
    
        if (grossSalary is >= 7_000)
        {
            addedAmount = 230;
            taxRate     = 5.75;
        }
        else if (grossSalary is >= 5_250)
        {
            addedAmount = 143;
            taxRate     = 5.00;
        }
        else if (grossSalary is >= 3_750)
        {
            addedAmount = 83;
            taxRate     = 4.00;
        }
        else if (grossSalary is >= 2_250)
        {
            addedAmount = 38;
            taxRate     = 3.00;
        }
        else if (grossSalary is >= 750)
        {
            addedAmount = 8;
            taxRate     = 2.00;
        }
        else // if grossSalary < 750:)
        {
            addedAmount = 0;
            taxRate     = 1.00;
        }
    }
            
    double taxAmount = addedAmount + (grossSalary * taxRate / 100.00);
    double net_pay = grossSalary - taxAmount;
    
    WriteLine("========================================================");
    WriteLine("- Georgia - State Income Tax -");
    WriteLine("--------------------------------------------------------");
    WriteLine($"Gross Salary:  {grossSalary:f}");
    WriteLine($"Filing Status: {filingStatus}");
    WriteLine($"Tax Rate:      {taxRate:f}%");
    WriteLine($"Tax Amount:    {taxAmount:f}");
    WriteLine($"Net Pay:       {net_pay:f}");
    WriteLine("========================================================");
  11. To execute, on the main menu, click Debug -> Start Without Debugging
  12. For the Gross Salary, type 5278.75 and press Enter
  13. For the Filing Status, type j and press Enter:
    ========================================================
     - Georgia - State Income Tax -
    ========================================================
    Enter the information for tax preparation
    Gross Salary:  5278.75
    Filing Status
    1 - Single
    s - Married Filing Separate
    j - Married Filing Joint or Head of Household
    Enter Filing Status: j
    ========================================================
    - Georgia - State Income Tax -
    --------------------------------------------------------
    Gross Salary:  5278.75
    Filing Status: Married Filing Joint or Head of Household
    Tax Rate:      4.00%
    Tax Amount:    321.15
    Net Pay:       4957.60
    ========================================================
    Press any key to close this window . . .
  14. Press T to close the window and return to your programming environment
  15. To execute again, on the main menu, click Debug -> Start Without Debugging
  16. For the Gross Salary, type 5278.75 and press Enter
  17. For the Filing Status, type s and press Enter:
    ========================================================
     - Georgia - State Income Tax -
    ========================================================
    Enter the information for tax preparation
    Gross Salary:  5278.75
    Filing Status
    1 - Single
    s - Married Filing Separate
    j - Married Filing Joint or Head of Household
    Enter Filing Status: s
    ========================================================
    - Georgia - State Income Tax -
    --------------------------------------------------------
    Gross Salary:  5278.75
    Filing Status: Married Filing Separate
    Tax Rate:      5.75%
    Tax Amount:    473.53
    Net Pay:       4805.22
    ========================================================
    Press any key to close this window . . .
  18. Press G to close the window and return to your programming environment
  19. To execute again, on the main menu, click Debug -> Start Without Debugging
  20. For the Gross Salary, type 5278.75 and press Enter
  21. For the Filing Status, type Separated from husband, living as a single person and press Enter:
    ========================================================
     - Georgia - State Income Tax -
    ========================================================
    Enter the information for tax preparation
    Gross Salary:  5278.75
    Filing Status
    1 - Single
    s - Married Filing Separate
    j - Married Filing Joint or Head of Household
    Enter Filing Status: Separated from husband, living as a single person
    ========================================================
    - Georgia - State Income Tax -
    --------------------------------------------------------
    Gross Salary:  5278.75
    Filing Status: Single
    Tax Rate:      5.00%
    Tax Amount:    406.94
    Net Pay:       4871.81
    ========================================================
    Press any key to close this window . . .
  22. Press B to close the window and return to your programming environment
  23. Follow the instructions in the beginning of this lesson to create a new Console App that supports .NET 6.0 (Long-Term Support)) named TaxPreparation03

A Binary Logical Conjunction

Remember that you can nest one condition in another condition as in:

if( condition1 )
    if( condition2 )
    statement(s)

Remember that you can (and in some cases you must) use curly brackets to delimit the section of a conditional statement:

if( condition1 )
{    
    if( condition2 )
    {
        statement(s)
    }
}

When you nest a condition, you are in fact indicating that "if condition1 verifies, (then) if condition2 verifies, do this...". Instead of nesting the second condition, in some (but not all) cases, you can combine the conditions. This operation is referred to as a conjunction, or a Boolean conjunction, or a logical conjunction. The operation is performed with the AND operator. The litteral formula of a Boolean conjunction is:

condition1 AND condition2

In C#, the AND operation is primarily done with the operator represented as an ampersand &. It can be represented as follows:

condition1 & condition2

As we saw in the previous lesson and previous sections, each condition is formulated as a Boolean operation with two operands separated by a Boolean operator:

operand1 Boolean-operator operand2

The whole expression can be written in the parenthesis of a conditional statement, as in:

if(condition1 & condition2)
    statement(s);

Therefore, if using a conditional statement, the whole Boolean conjunction can be formulated as follows:

if(operand1 operator1 operand2 & operand3 operator2 operand4)
    statement(s);

The (condition1 & condition2) operation is referred to as a binary conjunction or a logical binary conjunction. During the operation, the first condition, condition1, is checked. Then the second condition, condition2, also is checked (regardless of the result of the first condition).

You must formulate each condition to produce a true or a false result. The result is as follows:

The conjunction operation can be resumed as follows:

Condition-1 Contition 2 Condition-1 & Condition-2
True True True
True False False
False True False
False False False

Conjunctions and Boolean Operators

Introduction

We mentioned that each condition in a conjunction is formulated as a Boolean expression:

condition1 AND condition2

This means that you will use the Boolean operators we saw already but there are some details to keep in mind.

Checking for Equality

One of the operations you can perform in a conjunction is to check for equality. Since a variable cannot be equal to two values, you should use a different variable for each condition. Here is an example:

using static System.Console;

WriteLine("=======================================================================================================");
WriteLine("To grant you this job, we need to ask a few questions.");
Write("Do you have a college degree (undergraduate or graduate (Type 1 for Yes or another number for No)? ");
int degree = int.Parse(ReadLine());
WriteLine("-------------------------------------------------------------------------------------------------------");
Write("Do you hold a SECRET or equivalent security level (Type True or False):                            ");
bool security = bool.Parse(ReadLine());
        
WriteLine("-------------------------------------------------------------------------------------------------------");
        
if ( degree == 1 & security == true )
    WriteLine("Welcome on board.");
else
    WriteLine("We will get back to you...");
            
WriteLine("=======================================================================================================");

Here is an example of running the program:

=======================================================================================================
To grant you this job, we need to ask a few questions.
Do you have a college degree (undergraduate or graduate (Type 1 for Yes or another number for No)? 1
-------------------------------------------------------------------------------------------------------
Do you hold a SECRET or equivalent security level (Type True or False):                            TRUE
-------------------------------------------------------------------------------------------------------
Welcome on board.
=======================================================================================================

Press any key to close this window . . .

Here is another example of running the program:

=======================================================================================================
To grant you this job, we need to ask a few questions.
Do you have a college degree (undergraduate or graduate (Type 1 for Yes or another number for No)? 1000
-------------------------------------------------------------------------------------------------------
Do you hold a SECRET or equivalent security level (Type True or False):                            true
-------------------------------------------------------------------------------------------------------
We will get back to you...
=======================================================================================================

Press any key to close this window . . .

Isolating the Conditions of a Conjunction

Conditional statements can be difficult to read, especially when they are long. When it comes to conjunctions, to make your code easy to read, you can put each conditions in its own parentheses. Based on this, the above code can be written as follows:

using static System.Console;

WriteLine("=======================================================================================================");
WriteLine("To grant you this job, we need to ask a few questions.");
Write("Do you have a college degree (undergraduate or graduate (Type 1 for Yes or another number for No)? ");
int degree = int.Parse(ReadLine());
WriteLine("-------------------------------------------------------------------------------------------------------");
Write("Do you hold a SECRET or equivalent security level (Type True or False):                            ");
bool security = bool.Parse(ReadLine());
        
WriteLine("-------------------------------------------------------------------------------------------------------");
        
if( (degree == 1) & (security == true) )
    WriteLine("Welcome on board.");
else
    WriteLine("We will get back to you...");
            
WriteLine("=======================================================================================================");

Negating a Condition

Remember that, in a conjunction, each condition is formulated as a Boolean operation. To negate an logical operation, we already know that we can use the ! operator. You can apply this operator in a conjunction. You have various options.

Because a conjunction is a whole Boolean operation by itself, you can negate the whole conjunction. To do this, put the whole operaion in parentheses and precede it with the ! operator. Here is an example:

using static System.Console;

WriteLine("=======================================================================================================");
WriteLine("To grant you this job, we need to ask a few questions.");
Write("Do you have a college degree (undergraduate or graduate (Type 1 for Yes or another number for No)? ");
int degree = int.Parse(ReadLine());
WriteLine("-------------------------------------------------------------------------------------------------------");
Write("Do you hold a SECRET or equivalent security level (Type True or False):                            ");
bool security = bool.Parse(ReadLine());

WriteLine("-------------------------------------------------------------------------------------------------------");

if( !(degree == 1 & security == true) )
    WriteLine("The company management needs to investigate your application more seriously.");
else
    WriteLine("You are hired.");

WriteLine("=======================================================================================================");

Here is an example of running the program:

=======================================================================================================
To grant you this job, we need to ask a few questions.
Do you have a college degree (undergraduate or graduate (Type 1 for Yes or another number for No)? 2
-------------------------------------------------------------------------------------------------------
Do you hold a SECRET or equivalent security level (Type True or False):                            True
-------------------------------------------------------------------------------------------------------
The company management needs to investigate your application more seriously.
=======================================================================================================

Press any key to close this window . . .

If you want, you can negate only one of the conditions. In that case, that condition must be included in parentheses. Then, precede that condition with the ! operator. Here is an example:

using static System.Console;

WriteLine("Traffic Tickets Management");
WriteLine("This application allows the county to set the ticket amount from an image filmed by a traffic camera.");

WriteLine("=====================================================================================================");

int ticket = 90;

Write("Was the driver going at 15 miles above the speed limit (Type Yes or No)? ");
string speedAnswer = ReadLine();
WriteLine("------------------------------------------------------------------------------------------------------");
WriteLine("Road Status");
WriteLine("R - Regular traffic");
WriteLine("Z - School Zone");
Write("Enter the road status (Type R, S, or Z)?                                 ");
string status = ReadLine();

bool valid = speedAnswer == "Yes" & !(status == "Z");

if (valid == true)
    ticket = 45;

WriteLine("======================================================================================================");
WriteLine("Ticket Amount: {0}", ticket);
WriteLine("======================================================================================================");

Here is an example of running the program:

Traffic Tickets Management
This application allows the county to set the ticket amount from an image filmed by a traffic camera.
=====================================================================================================
Was the driver going at 15 miles above the speed limit (Type Yes or No)? Yes
------------------------------------------------------------------------------------------------------
Road Status
R - Regular traffic
Z - School Zone
Enter the road status (Type R, S, or Z)?                                 R
======================================================================================================
Ticket Amount: 45
======================================================================================================

Press any key to close this window . . .

If necessary, you can negate each of both conditions. Here is an example:

using static System.Console;

WriteLine("=======================================================================================================");
WriteLine("To grant you this job, we need to ask a few questions.");
Write("Do you have a college degree (undergraduate or graduate (Type 1 for Yes or another number for No)? ");
int degree = int.Parse(ReadLine());
WriteLine("-------------------------------------------------------------------------------------------------------");
Write("Do you hold a SECRET or equivalent security level (Type True or False):                            ");
bool security = bool.Parse(ReadLine());

WriteLine("-------------------------------------------------------------------------------------------------------");

if( !(degree == 1) & !(security == true) )
    WriteLine("We will get back to you...");
else
    WriteLine("You employment application is currently under review.");

WriteLine("=======================================================================================================");

Here is an example of running the program:

=======================================================================================================
To grant you this job, we need to ask a few questions.
Do you have a college degree (undergraduate or graduate (Type 1 for Yes or another number for No)? 5
-------------------------------------------------------------------------------------------------------
Do you hold a SECRET or equivalent security level (Type True or False):                            True
-------------------------------------------------------------------------------------------------------
You employment application is currently under review.
=======================================================================================================

Press any key to close this window . . .

Checking for Non-Equality

In Boolean algebra, to check whwether a certain variable holds a value different from a constant you have, you can use the != operator. Because a variable can easily be different from two values, you can use the same variable on two conditions of a conjunction. Here are examples:

using static System.Console;

WriteLine("Traffic Tickets Management");
WriteLine("This application allows the county to set the ticket amount from an image filmed by a traffic camera.");
WriteLine("-----------------------------------------------------------------------------------------------------");

int ticket = 45;

WriteLine("Road Status");
WriteLine("R - Regular traffic");
WriteLine("S - Sensitive Area");
WriteLine("Z - School Zone");
WriteLine("U - Unknown or information not available");
Write("Enter the road status (Type R, S, or Z)? ");
string status = ReadLine();

bool valid = status != "R" & status != "U";

if (valid == true)
    ticket = 90;

WriteLine("=====================================================================================================");
WriteLine("Ticket Amount: {0}", ticket);
WriteLine("=====================================================================================================");

Here is an example of testing the program:

Traffic Tickets Management
This application allows the county to set the ticket amount from an image filmed by a traffic camera.
-----------------------------------------------------------------------------------------------------
Road Status
R - Regular traffic
S - Sensitive Area
Z - School Zone
U - Unknown or information not available
Enter the road status (Type R, S, or Z)? R
=====================================================================================================
Ticket Amount: 45
=====================================================================================================

Press any key to close this window . . .

Here is another example of testing the program:

Traffic Tickets Management
This application allows the county to set the ticket amount from an image filmed by a traffic camera.
-----------------------------------------------------------------------------------------------------
Road Status
R - Regular traffic
S - Sensitive Area
Z - School Zone
U - Unknown or information not available
Enter the road status (Type R, S, or Z)? S
=====================================================================================================
Ticket Amount: 90
=====================================================================================================

Press any key to close this window . . .

A Conjunction for Non-Equivalence

The <, <=, >, and >= operators are also available for conditional statements. You can apply any of those operators to a condition of a conjunction. You can use the same variable for each condition or you can use a different variable for each condition. Here is an example that checks that a number is in a certain range:

using static System.Console;

WriteLine("================================================================");

WriteLine("To grant you this job, we need to ask a few questions.");
WriteLine("Levels of Security Clearance:");
WriteLine("0. Unknown or None");
WriteLine("1. Non-Sensitive");
WriteLine("2. National Security - Non-Critical Sensitive");
WriteLine("3. National Security - Critical Sensitive");
WriteLine("4. National Security - Special Sensitive");
WriteLine("----------------------------------------------------------------");
Write("Type your level (1-4): ");
int level = int.Parse(ReadLine());
        
WriteLine("================================================================");
        
if( level is >= 2 & level is <= 4 )
    WriteLine("Welcome on board.");
else
    WriteLine("We will get back to you...");

WriteLine("================================================================");

Here is an example of running the program:

================================================================
To grant you this job, we need to ask a few questions.
Levels of Security Clearance:
0. Unknown or None
1. Non-Sensitive
2. National Security - Non-Critical Sensitive
3. National Security - Critical Sensitive
4. National Security - Special Sensitive
----------------------------------------------------------------
Type your level (1-4): 2
================================================================
Welcome on board.
================================================================

Press any key to close this window . . .

Here is another example of running the program:

================================================================
To grant you this job, we need to ask a few questions.
Levels of Security Clearance:
0. Unknown or None
1. Non-Sensitive
2. National Security - Non-Critical Sensitive
3. National Security - Critical Sensitive
4. National Security - Special Sensitive
----------------------------------------------------------------
Type your level (1-4): 1
================================================================
We will get back to you...
================================================================

Press any key to close this window . . .

In the same way, you can use a combination of the Boolean operators any appropriate way you want. Here are examples where one condition uses the == operator white the other condition uses a >= operator:

using static System.Console;

string name = "Gabrielle Towa";
double timeWorked = 42.50;
string status = "Full-Time";
bool verdict = status == "Full-Time" & timeWorked is >= 40.00;

WriteLine("Employee Name:               {0}", name);
WriteLine("Time Worked:                 {0}", timeWorked);
WriteLine("Employment Status:           {0}", status);
WriteLine("Condition-1 AND Condition-2: {0}", verdict);
WriteLine("--------------------------------------------------------------------------------------");

// Both conditions are True:
if ( verdict == true )
    WriteLine("The time sheet has been approved.");
else
    WriteLine("Part-time employees are not allowed to work overtime.");
WriteLine("======================================================================================");

name   = "Stephen Anders";
status = "Full-Time";
timeWorked = 38.00;
verdict = status == "Full-Time" & timeWorked is >= 40.00;

WriteLine("Employee Name:               {0}", name);
WriteLine("Time Worked:                 {0}", timeWorked);
WriteLine("Employment Status:           {0}", status);
WriteLine("Condition-1 AND Condition-2: {0}", verdict);
WriteLine("--------------------------------------------------------------------------------------");

// The first condition is True AND the second condition is False:
if (verdict == true)
    WriteLine("The time sheet has been approved.");
else
    WriteLine("Time Sheet under review: Every full-time employee must work at least 40 hours a week.");
WriteLine("======================================================================================");

name    = "Rose Sandt";
status  = "Part-Time";
timeWorked = 44.00;
verdict = status == "Full-Time" & timeWorked is >= 40.00;

WriteLine("Employee Name:               {0}", name);
WriteLine("Time Worked:                 {0}", timeWorked);
WriteLine("Employment Status:           {0}", status);
WriteLine("Condition-1 AND Condition-2: {0}", verdict);
WriteLine("--------------------------------------------------------------------------------------");

// The first condition is False AND the second condition is True:
if (verdict == true)
    WriteLine("The time sheet has been approved.");
else
    WriteLine("Part-time employees are not allowed to work overtime.");
WriteLine("======================================================================================");

name = "Joseph Lee";
status = "Part-Time";
timeWorked = 36.50;
verdict = status == "Full-Time" & timeWorked is >= 40.00;

WriteLine("Employee Name:               {0}", name);
WriteLine("Time Worked:                 {0}", timeWorked);
WriteLine("Employment Status:           {0}", status);
WriteLine("Condition-1 AND Condition-2: {0}", verdict);
WriteLine("--------------------------------------------------------------------------------------");

// The first condition is False AND the second condition is False:
if (verdict == true)
    WriteLine("Part-time employees work part-time.");
else
    WriteLine("Part-time employees are not allowed to work overtime.");
WriteLine("======================================================================================");

This would produce:

Employee Name:               Gabrielle Towa
Time Worked:                 42.5
Employment Status:           Full-Time
Condition-1 AND Condition-2: True
--------------------------------------------------------------------------------------
The time sheet has been approved.
======================================================================================
Employee Name:               Stephen Anders
Time Worked:                 38
Employment Status:           Full-Time
Condition-1 AND Condition-2: False
--------------------------------------------------------------------------------------
Time Sheet under review: Every full-time employee must work at least 40 hours a week.
======================================================================================
Employee Name:               Rose Sandt
Time Worked:                 44
Employment Status:           Part-Time
Condition-1 AND Condition-2: False
--------------------------------------------------------------------------------------
Part-time employees are not allowed to work overtime.
======================================================================================
Employee Name:               Joseph Lee
Time Worked:                 36.5
Employment Status:           Part-Time
Condition-1 AND Condition-2: False
--------------------------------------------------------------------------------------
Part-time employees are not allowed to work overtime.
======================================================================================

Press any key to close this window . . .

In the above example, we wrote each conjunction as one unit (such as status == "Full-Time" & timeWorked is >= 40.00). Remember that, when creating a logical conjunction, to make your code easy to read, you should put each condition in its own parenthesis. Here are examples:

using static System.Console;

string name = "Gabrielle Towa";
double timeWorked = 42.50;
string status = "Full-Time";

WriteLine("Employee Name:     {0}", name);
WriteLine("Time Worked:       {0}", timeWorked);
WriteLine("Employment Status: {0}", status);
WriteLine("--------------------------------------------------------------------------------------");

// Both conditions are True:
if( (status == "Full-Time") & (timeWorked is >= 40.00) )
    WriteLine("The time sheet has been approved.");
else
    WriteLine("Part-time employees are not allowed to work overtime.");
WriteLine("======================================================================================");

name   = "Stephen Anders";
status = "Full-Time";
timeWorked = 38.00;

WriteLine("Employee Name:     {0}", name);
WriteLine("Time Worked:       {0}", timeWorked);
WriteLine("Employment Status: {0}", status);
WriteLine("--------------------------------------------------------------------------------------");

// The first condition is True AND the second condition is False:
if( (status == "Full-Time") & (timeWorked is >= 40.00) )
    WriteLine("The time sheet has been approved.");
else
    WriteLine("Time Sheet under review: Every full-time employee must work at least 40 hours a week.");
WriteLine("======================================================================================");

name    = "Rose Sandt";
status  = "Part-Time";
timeWorked = 44.00;

WriteLine("Employee Name:     {0}", name);
WriteLine("Time Worked:       {0}", timeWorked);
WriteLine("Employment Status: {0}", status);
WriteLine("--------------------------------------------------------------------------------------");

// The first condition is False AND the second condition is True:
if( (status == "Full-Time") & (timeWorked is >= 40.00) )
    WriteLine("The time sheet has been approved.");
else
    WriteLine("Part-time employees are not allowed to work overtime.");
WriteLine("======================================================================================");

name = "Joseph Lee";
status = "Part-Time";
timeWorked = 36.50;

WriteLine("Employee Name:     {0}", name);
WriteLine("Time Worked:       {0}", timeWorked);
WriteLine("Employment Status: {0}", status);
WriteLine("--------------------------------------------------------------------------------------");

// The first condition is False AND the second condition is False:
if( (status == "Full-Time") & (timeWorked is >= 40.00) )
    WriteLine("Part-time employees work part-time.");
else
    WriteLine("Part-time employees are not allowed to work overtime.");
WriteLine("======================================================================================");

A Binary Conditional Conjunction

To further assist you in performing logical conjunctions, the C-based languages, and C# is one of them, support the classic AND operator represented by two ampersands &&. The operation is referred to as binary conditional conjunction. As we saw for the & operator, the formula for an && operation can be represented as follows:

condition1 && condition2

Also, the whole operation can be included in the parentheses of a conditional statement. The main difference between the & and the && operations in the evaluation fo the second condition. In the && operation, the first condition, condition1, is first evaluated. If that first condition is true, then the second condition in turn is evaluated. If the first condition is false (or not true), the second condition is not evaluated and the whole operation is false. The operation can be resumed as follows:

The binary conditional conjunction operation can be resumed as follows:

Condition-1 Contition 2 Condition-1 & Condition-2 Condition-1 && Condition-2
True True True True
True False False False
False True False False
False False False False

Each condition is primarily independent of the other. As a result, each condition can deal with a variable to compare to a value. Here is an example:

AND for a Conjunction

A condition of a Boolean conjunction can use the "Less Than" (<), the "Less Than or Equal" (<=), the "Greater Than" (>), or the "Greater Than or Equal" (>=) operator. For any of these operators, to make your code easy to read, you can use an operator named and. This operator is combined with the is operator. The formula to follow is:

operand is condition1 and condition2

Start with variable that both conditions use. The variable must be followed by the is operator. Then formulate each conditionl using the "Less Than" (<), the "Less Than or Equal" (<=), the "Greater Than" (>), or the "Greater Than or Equal" (>=) operator. Separate both conditions with the and operator.

Practical LearningPractical Learning: Introducing Boolean Conjunctions

  1. Change the document as follows:
    using static System.Console;
    
    WriteLine("============================================");
    WriteLine(" - Missouri - State Income Tax -");
    WriteLine("============================================");
    
    double taxRate;
    int amountAdded;
    
    WriteLine("Enter the information for tax preparation");
    Write("Gross Salary:        ");
    double grossSalary = double.Parse(ReadLine());
    
    //Missouri
    if(grossSalary is >= 0.00 and <= 106)
    {
        amountAdded = 0;
        taxRate = 0.00;
    }
    else if (grossSalary is > 106 and <= 1_073)
    {
        amountAdded = 0;
        taxRate = 1.50;
    }
    else if (grossSalary is > 1_073 and <= 2_146)
    {
        amountAdded = 16;
        taxRate = 2.00;
    }
    else if (grossSalary is > 2_146 and <= 3_219)
    {
        amountAdded = 37;
        taxRate = 2.50;
    }
    else if (grossSalary is > 3_219 and <= 4_292)
    {
        amountAdded = 64;
        taxRate = 3.00;
    }
    else if (grossSalary is > 4_292 and <= 5_365)
    {
        amountAdded = 96;
        taxRate = 3.50;
    }
    else if (grossSalary is > 5_365 and <= 6_438)
    {
        amountAdded = 134;
        taxRate = 4.00;
    }
    else if (grossSalary is > 6_438 and <= 7_511)
    {
        amountAdded = 177;
        taxRate = 4.50;
    }
    else if (grossSalary is > 7_511 and <= 8_584)
    {
        amountAdded = 225;
        taxRate = 5.00;
    }
    else // if(grossSalary is > 8_584)
    {
        amountAdded = 279;
        taxRate = 5.40;
    }
    
    double taxAmount = amountAdded + (grossSalary * taxRate / 100.00);
    double netPay = grossSalary - taxAmount;
    
    WriteLine("==============================================");
    WriteLine("- Missouri - State Income Tax -");
    WriteLine("----------------------------------------------");
    WriteLine($"Gross Salary:        {grossSalary:f}");
    WriteLine($"Tax Rate:            {taxRate:f}%");
    WriteLine($"Amount Added:        {amountAdded:f}");
    WriteLine("----------------------------------------------");
    WriteLine($"Tax Amount:          {taxAmount:f}");
    WriteLine($"Net Pay:             {netPay:f}");
    WriteLine("==============================================");
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging
  3. For the Gross Salary, type a natural number such as 3688.93 and press Enter:
    ============================================
     - Missouri - State Income Tax -
    ============================================
    Enter the information for tax preparation
    Gross Salary:        3688.97
    ==============================================
    - Missouri - State Income Tax -
    ----------------------------------------------
    Gross Salary:        3688.97
    Tax Rate:            3.00%
    Amount Added:        64.00
    ----------------------------------------------
    Tax Amount:          174.67
    Net Pay:             3514.30
    ==============================================
    Press any key to close this window . . .
  4. Press V to close the window and return to your programming environment
  5. To make your code easy to read, you can include each condition in its parentheses. For examples, change the code as follows:
    using static System.Console;
    
    WriteLine("============================================");
    WriteLine(" - Missouri - State Income Tax -");
    WriteLine("============================================");
    
    double taxRate;
    int amountAdded;
    
    WriteLine("Enter the information for tax preparation");
    Write("Gross Salary:        ");
    double grossSalary = double.Parse(ReadLine());
    
    //Missouri
    if(grossSalary is (>= 0.00) and (<= 106))
    {
        amountAdded = 0;
        taxRate = 0.00;
    }
    else if(grossSalary is (> 106) and (<= 1_073))
    {
        amountAdded = 0;
        taxRate = 1.50;
    }
    else if(grossSalary is (> 1_073) and (<= 2_146))
    {
        amountAdded = 16;
        taxRate = 2.00;
    }
    else if(grossSalary is (> 2_146) and (<= 3_219))
    {
        amountAdded = 37;
        taxRate = 2.50;
    }
    else if(grossSalary is (> 3_219) and (<= 4_292))
    {
        amountAdded = 64;
        taxRate = 3.00;
    }
    else if(grossSalary is (> 4_292) and (<= 5_365))
    {
        amountAdded = 96;
        taxRate = 3.50;
    }
    else if(grossSalary is (> 5_365) and (<= 6_438))
    {
        amountAdded = 134;
        taxRate = 4.00;
    }
    else if(grossSalary is (> 6_438) and (<= 7_511))
    {
        amountAdded = 177;
        taxRate = 4.50;
    }
    else if(grossSalary is (> 7_511) and (<= 8_584))
    {
        amountAdded = 225;
        taxRate = 5.00;
    }
    else // if(grossSalary is > 8_584)
    {
        amountAdded = 279;
        taxRate = 5.40;
    }
    
    double taxAmount = amountAdded + (grossSalary * taxRate / 100.00);
    double netPay = grossSalary - taxAmount;
    
    WriteLine("==============================================");
    WriteLine("- Missouri - State Income Tax -");
    WriteLine("----------------------------------------------");
    WriteLine($"Gross Salary:        {grossSalary:f}");
    WriteLine($"Tax Rate:            {taxRate:f}%");
    WriteLine($"Amount Added:        {amountAdded:f}");
    WriteLine("----------------------------------------------");
    WriteLine($"Tax Amount:          {taxAmount:f}");
    WriteLine($"Net Pay:             {netPay:f}");
    WriteLine("==============================================");
  6. To execute again, on the main menu, click Debug -> Start Without Debugging
  7. For the Gross Salary, type a natural number such as 7884.65 and press Enter:
    ============================================
     - Missouri - State Income Tax -
    ============================================
    Enter the information for tax preparation
    Gross Salary:        7884.65
    ==============================================
    - Missouri - State Income Tax -
    ----------------------------------------------
    Gross Salary:  7884.65
    Tax Rate:      5.00%
    Amount Added:  225.00
    ----------------------------------------------
    Tax Amount:    619.23
    Net Pay:       7265.42
    ==============================================
    Press any key to close this window . . .
  8. Press T to close the window and return to your programming environment

Combining Various Conjunctions

Depending on your goal, if two conditions are not enough, you can create as many conjunctions as you want. The formula to follow is:

condition1 && condition2 && condition3 && . . . && condition_n

When the expression is checked, if any of the operations is false, the whole operation is false. The only time the whole operation is true is if all the operations are true.

Of course, you can nest a Boolean condition inside another conditional statement.

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2023, FunctionX Sunday 13 November 2022 Next