If-Else If-Else Statement

suggest change

Following on from the If-Else Statement example, it is now time to introduce the Else If statement. The Else If statement follows directly after the If statement in the If-Else If-Else structure, but intrinsically has a similar syntax to the If statement. It is used to add more branches to the code than what a simple If-Else statement can.

In the example from If-Else Statement, the example specified that the score goes up to 100; however there were never any checks against this. To fix this, let's modify the method from If-Else Statement to look like this:

static void PrintPassOrFail(int score)
{
    if (score > 100) // If score is greater than 100
    {
        Console.WriteLine("Error: score is greater than 100!");
    }
    else if (score < 0) // Else If score is less than 0
    {
        Console.WriteLine("Error: score is less than 0!");
    }
    else if (score >= 50) // Else if score is greater than or equal to 50
    {
        Console.WriteLine("Pass!");
    }
    else // If none of the above match, score is from 0 through 49
    {
        Console.WriteLine("Fail!");
    }
}

The conditions are tested from top to bottom until one is true; later branches are then skipped. In this new update of the method, we’ve added two new branches to now accommodate for the score going out of bounds.

For example, if we now called the method in our code as PrintPassOrFail(110);, the output would be a Console Print saying Error: score is greater than 100!; and if we called the method in our code like PrintPassOrFail(-20);, the output would say Error: score is less than 0!.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents