Code

if statements

if statements ( selection structure )

With if statement, you can tell the computer to make a choice by evaluating a Boolean logical expression (true or false) called condition. It allows you to tell the computer whether to run the code inside the block, based on the condition or set of conditions.

if With a single statement

if with a single statement

Run Demo

OUTPUT

Condition is true.
Condition is true on a single line.

With a block of statements

if condition

The value of a number variable is 8. So the expression (number > 7) is evaluated to true because 8 is greater than 7. Hence, the statements inside the body of if block are executed. If you change the value of a number variable from 8 to 6 then the expression will return false, which will ignore the execution of if body {...}.

Run Demo

OUTPUT

8 is greater than 7
Condition is true

if…else Statement

If-else statement with Else execute

In the example above, the value of a number variable is 6. So the expression (number > 7) is evaluated to false because 6 is less than 7. Hence, the code inside else block is executed.

Run Demo

OUTPUT

6 is less than 7
Condition is false

if…else if…else Statement

if-elseif-else
if-elseif-else example 2

Run Demo

OUTPUT

Only females are allowed.

Nested if Statement

string gender = "Male";
int age = 18;

if (gender == "Male") // true
{
    Console.WriteLine("Only males are allowed.");

    if (age >= 18) // true
        Console.WriteLine("I am 18+.");
    else
        Console.WriteLine("I am not 18+.");
}
else if (gender == "Female")
{
    Console.WriteLine("Only females are allowed.");
}
else
{
    Console.WriteLine("Unknown gender!");
}

Run Demo

OUTPUT

Only males are allowed.
I am 18+.

Add Comment

Click here to post a comment

Subscribe

Most Popular

Popular Video