Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are multiple 'if' statements and 'if-else-if' statements the same for mutually exclusive conditions?

Is there any difference between writing multiple if statements and if-else-if statements ?

When I tried to write a program with multiple if statements, It did not give the expected results, But it worked with if-else-if.

The conditions were mutually exclusive.

like image 554
arnav bhartiya Avatar asked Apr 29 '15 13:04

arnav bhartiya


People also ask

What is the difference between multiple if statements and else if?

If statements are executed independent of one another; each one will run. Else if statements only execute if the previous if s fail.

Are if else statements mutually exclusive?

Use two if statements if both if statement conditions could be true at the same time. In this example, both conditions can be true. You can pass and do great at the same time. Use an if/else statement if the two conditions are mutually exclusive meaning if one condition is true the other condition must be false.

Can you have multiple if else statements?

It is possible to nest multiple IF functions within one Excel formula. You can nest up to 7 IF functions to create a complex IF THEN ELSE statement.

What is better than multiple if statements?

Switch statement works better than multiple if statements when you are giving input directly without any condition checking in the statements. Switch statement works well when you want to increase the readability of the code and many alternative available.


1 Answers

When you write multiple if statements, it's possible that more than one of them will be evaluated to true, since the statements are independent of each other.

When you write a single if else-if else-if ... else statement, only one condition can be evaluated to true (once the first condition that evaluates to true is found, the next else-if conditions are skipped).

You can make multiple if statements behave like a single if else-if .. else statement if each of the condition blocks breaks out of the block that contains the if statements (for example, by returning from the method or breaking from a loop).

For example :

public void foo (int x)
{
    if (x>7) {
        ...
        return;
    }
    if (x>5) {
        ...
        return;
    }    
}

Will have the same behavior as :

public void foo (int x)
{
    if (x>7) {
        ...
    }
    else if (x>5) {
        ...
    }
}

But without the return statements it will have different behavior when x>5 and x>7 are both true.

like image 136
Eran Avatar answered Oct 19 '22 14:10

Eran