CONDITIONAL STRUCTURES IN C SHARP

C sharpIn programs it often happens that blocks of code are executed when certain conditions arise. Suppose for example, to introduce conditional structures, that our program asks the user his age and based on this decides whether he can drive or not.

int age = 0;

Console.WriteLine (“Enter your age….”);

String eta = Console.ReadLine ();

age = Convert.ToInt32 (eta);

Console.WriteLine ($”You introduced {age} years.”);

The piece of code I gave you above asks via a Console.WriteLine to enter the age, then with a Console.ReadLine() which you have never seen yet but which basically does nothing more than take the input value that was typed by the user and places it in a string. A person’s age is a numeric value so with the Convert.ToInt32(age) we transform the user input into an integer. Obviously for reasons of simplicity the program deliberately does not check whether the user types other things instead of typing a number. In this case an exception is thrown by the Convert.ToInt32 method and the program ends.

THE IF ( IF ) STATEMENT

if ( boolean condition ){

Block of code executed if the condition is true (true);

}

A Boolean condition is any condition that at the end of the evaluation returns a Boolean value (true or false, true or false) using the logical operators we have already seen and the comparison operators. Based on what has been said, our program could continue by doing a conditional test to establish whether the user is an adult or not.

int age = 0;

Console.WriteLine (“Enter your age….”);

String eta = Console.ReadLine ();

age = Convert.ToInt32 (eta);

Console.WriteLine ($”You introduced {age} years.”);

if ( age >= 18 )

Consoles.WriteLine (“You are an adult so you can drive.”);

NB: If the code block contains only one line then the curly brackets can be omitted.

But let’s make the code even more specific by introducing the else clause and the else if clause . These two clauses are optional however if there is an else statement it must be placed at the end of the code block.

int age = 0;

Console.WriteLine (“Enter your age….”);

String eta = Console.ReadLine ();

age = Convert.ToInt32 (eta);

Consoles.WriteLine ( $”You have introduced {age} years.”);

if ( age< 18 )

Console.WriteLine (“You are a minor so you cannot drive.”);

else if ( age == 18 )

Console.WriteLine (“You are an adult so you can drive.”);

else if ( age> 18 && age< 90 )

Console.WriteLine (“You are an adult so you can drive.”);

else

Console.WriteLine ($”Invalid value you have {age} years”);

NB: I gave you the equality operator == to make you understand the difference with the assignment operator =

TRUTH TABLES LOGICAL OPERATORS

LOGICAL AND OPERATOR (&&)

A

B

Y

false

false

false

false

true

false

true

false

false

true

true

true

LOGICAL OR OPERATOR (||)

A

B

Y

false

false

false

false

true

true

true

false

true

true

true

true

LOGICAL OPERATOR NOT (!)

A

Y

false

true

true

false

CONDITIONAL STRUCTURES IN C SHARP THE CONDITIONAL OPERATOR

We said that in C# the operators in most cases have two operands, then there are the unary operators that we have already seen and we mentioned the fact that C# provides a ternary operator (or conditional operator) that acts on three operands . Now we will see it in detail by simplifying the previously written code into a single statement.

( boolean condition ) ? value true : value false ;

The ? is called a ternary operator.

int age = 0;

Console.WriteLine (“Enter your age….”);

String eta = Console.ReadLine ();

age = Convert.ToInt32 (eta);

Console.WriteLine ( $”You have introduced {age} years.”);

if ( age< 18 )

Console.WriteLine (“You are a minor so you cannot drive.”);

else if ( age == 18 )

Console.WriteLine (“You are an adult so you can drive.”);

else if ( age> 18 && age< 90 )

Console.WriteLine (“You are an adult so you can drive.”);

else

Console.WriteLine ($”You have entered an invalid value{age} years”);

//TERNARY OPERATOR

String s = ( ( age == 18 || ( age>18 && age<90 )) ? “You are of legal age and can drive”:”You are not old enough to drive.”);

How do you see the ternary operator ? it significantly reduces the amount of code to be written, but this is at the expense of readability.

CONDITIONAL STRUCTURES IN C SHARP THE STATEMENT SWITCH

Types allowed in the switch:

  • Boolean
  • Integral Types
  • String
  • Enumeration

If the value of the variable is equal to the value specified in a case statement then that block of code is executed. It is important to underline that each case must have a break statement at the end of the code block that immediately interrupts the switch and the program flow switches to executing the statement immediately after the switch. It too must be enclosed in a pair of curly brackets. It is possible to specify the default statement that is executed when no case statement has been executed.

VISUAL STUDIO POST CODE

using System;

namespace StruttureCondizionali;

internal class Program
{
    private static void Main(string[] args)
    {
        var age = 0;
        Console.WriteLine("Inserisci la tua età....");
        var eta = Console.ReadLine();
        age = Convert.ToInt32(eta);
        Console.WriteLine($"Hai introdotto {age} anni.");
        if (age < 18)
            Console.WriteLine("Nello stato Italiano sei minorenne quindi non puoi guidare.");
        else if (age == 18)
            Console.WriteLine("Nello stato Italiano sei maggiorenne quindi puoi guidare.");
        else if (age > 18 && age < 90)
            Console.WriteLine("Nello stato Italiano sei maggiorenne quindi puoi guidare.");
        else
            Console.WriteLine($"Hai immesso un valore non valido hai {age} anni");
        //L'OPERATORE TERNARIO */
        Console.WriteLine(age == 18 || (age > 18 && age < 90)
            ? "Sei maggiorenne puoi guidare"
            : "Non hai l'età per guidare.");

        //LO STATEMENT SWITCH
        var myVar = 50;
        switch (myVar)
        {
            case 10:
            {
                Console.WriteLine(10);
                break;
            }
            case 20:
            case 30:
            case 40:
            {
                Console.WriteLine("20 ,30, 40");
                break;
            }
            case 50:
            {
                Console.WriteLine(50);
                break;
            }
            default:
            {
                Console.WriteLine("un altro valore");
                break;
            }
        }

        /*--VEDIAMO COME POSSIAMO USARE LO SWITCH PER GESTIRE L'ETA'
        DI UNA PERSONA.*/
        switch (age)
        {
            case < 18:
            {
                Console.WriteLine("Nello stato Italiano sei minorenne quindi non puoi guidare.");
                break;
            }
            case 18:
            case int when age > 18 && age < 90:
            {
                Console.WriteLine("Nello stato Italiano sei maggiorenne quindi puoi guidare.");
                break;
            }
            default:
            {
                Console.WriteLine($"Hai immesso un valore non valido {age} anni.");
                break;
            }
        }
    }
}

IN-DEPTH ON CONDITIONAL STRUCTURES

In C#, conditional structures are used to execute different blocks of code based on certain conditions. The main conditional structures in C# are if , else if , else , switch , and the ternary operator ( ?: ). Here is an overview of each of these facilities:

If, Else If, ​​Else

The most common conditional structure is the if statement, often combined with else if and else .

Syntax:

if ( condition )
{
// Code to execute if the condition is true
}
else if ( otherCondition )
{
// Code to execute if otherCondition is true
}
else
{
// Code to execute if none of the above conditions are true
}

Example:

int x = 10;

if ( x > 0 )
{
Console.WriteLine(“x is positive”);
}
else if ( x < 0 )
{
Console.WriteLine(“x is negative”);
}
else
{
Console.WriteLine(“x is zero”);
}

Switches

The switch structure is useful when you want to compare the value of a variable with multiple possible values.

Syntax:

switch ( variable )
{
case value1:
// Code to execute if variable equals value1
break;
case value2:
// Code to execute if variable equals value2
break;
// Other cases…
default :
// Code to execute if none of the above cases are satisfied
break;
}

Example:

int day = 3;

switch ( day )
{
case 1:
Console.WriteLine(” Monday “);
break ;
case 2:
Console.WriteLine(” Tuesday “);
break ;
case 3:
Console.WriteLine(” Wednesday “);
break;
case 4:
Console.WriteLine(” Thursday “);
break;
case 5:
Console.WriteLine(” Friday “);
break ;
case 6:
Console.WriteLine(” Saturday “);
break ;
case 7:
Console.WriteLine(” Sunday “);
break ;
default :
Console.WriteLine(” Invalid day “);
break ;
}

Ternary operator

The ternary operator ( ?: ) is a concise way of writing an if-else statement.

Syntax:

condition ? expression1 : expression2 ;

Example:

int x = 10;
string result = ( x > 0) ? ” x is positive ” : ” x is negative or zero “;
Console.WriteLine ( result );

LINKS TO PREVIOUS POSTS