[c] What are the differences between if, else, and else if?

I am trying to discern the difference between

if 
else 
else if 

When do you use them and when not?

I have a homework assignment with a ton of instances and I am running into code error due to not knowing the differences between each.

Can someone please define how to use these?

This question is related to c

The answer is


What the if says:

Whether I'm true or not, always check other conditions too.

What the else if says:

Only check other conditions if i wasn't true.


The else if can be used in conjunction with 'if', and 'else' to further break down the logic

//if less than zero
if( myInt < 0){
      //do something
}else if( myInt > 0 && myInt < 10){
//else if between 0 and 10      
      //do something
}else{
//else all others  
      //do something
}

If and else if both are used to test the conditions.

I take case of If and else..

In the if case compiler check all cases Wether it is true or false. if no one block execute then else part will be executed.

in the case of else if compiler stop the flow of program when it got false value. it does not read whole program.So better performance we use else if.

But both have their importance according to situation

i take example of foor ordering menu if i use else if then it will suit well because user can check only one also. and it will give error so i use if here..

 StringBuilder result=new StringBuilder();  
            result.append("Selected Items:");  
            if(pizza.isChecked()){  
                result.append("\nPizza 100Rs");  
                totalamount+=100;  
            }  
            if(coffe.isChecked()){  
                result.append("\nCoffe 50Rs");  
                totalamount+=50;  
            }  
            if(burger.isChecked()){  
                result.append("\nBurger 120Rs");  
                totalamount+=120;  
            }  
            result.append("\nTotal: "+totalamount+"Rs");  
            //Displaying the message on the toast  
            Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_LONG).show();  
        }  

now else if case

if (time < 12) {
    greeting = "Good morning";
} else if (time < 22) {
    greeting = "Good day";
} else {
    greeting = "Good evening";
}

here only satisfy one condition.. and in case of if multiple conditions can be satisfied...


you can think of the if and else as a pair, that satisfies two actions for one given condition.
ex: if it rains, take an umbrella else go without an umbrella.
there are two actions

  • go with an umbrella
  • go without an umbrella

and both the two actions are bound to one condition, i.e is it raining?

now, consider a scenario where there are multiple conditions and actions, bound together.
ex: if you are hungry and you are not broke, enjoy your meal at kfc, else if you are hungry but you are broke, try to compromise, else if you are not hungry, but you just want to hangout in a cafe, try startbucks, else do anything, just don't ask me about hunger or food. i have got bigger things to worry.
the else if statement to to string together all the actions that falls in between the if and the else conditions.


if (condition)
{
  thingsToDo()..
} 
else if (condition2)
{
  thingsToDoInTheSecondCase()..
}
else
{
  thingsToDoInOtherCase()..
}

If, else and else if are all constructs to help 'branch' code. Basically, you employ them whenever you want to make a decision.

An example would be 'if it's sunny, I'll go outside. otherwise, I'll stay inside'

In code (ignoring the extra stuff)

if (sunny) {
  goOutside();
}
else {
  stayInside();
}

You CAN use 'else if' statements if you want to add 'additional' conditions. Extending the previous example, "if it's sunny, I'll go outside. If it's stormy, I'll go into the basement otherwise I'll stay inside"

In code

if (sunny) {
  goOutside();
}
else if (stormy) {
  goDownstairs();
}
else {
  stayInside();
}

EDIT section:

Here is how you can write multiple ifs as and conditions. The following example can be written in at least two ways:

'If it's sunny and warm, go outside. If it's sunny and cold, do nothing'

if (sunny) {
   if (warm) {
     goOutside();
   }
   else if (cold) {
     doNothing();
   }
}

OR

if (sunny && warm) {
   goOutside();
}
else if (sunny && cold) {
   doNothing();
}

They mean exactly what they mean in English.

IF a condition is true, do something, ELSE (otherwise) IF another condition is true, do something, ELSE do this when all else fails.

Note that there is no else if construct specifically, just if and else, but the syntax allows you to place else and if together, and the convention is not to nest them deeper when you do. For example:

if( x )
{
    ...
}
else if( y )
{
    ...
}
else
{
    ...
}

Is syntactically identical to:

if( x )
{
    ...
}
else 
{
    if( y )
    {
        ...
    }
    else
    {
        ...
    }
}

The syntax in both cases is:

if *<statment|statment-block>* else *<statment|statment-block>*

and if is itself a statment, so that syntax alone supports the use of else if


Those are the basic decision orders that you have in most of the programming language; it helps you to decide the flow of actions that your program is gonna do. The if is telling the compiler that you have a question, and the question is the condition between parenthesis

if (condition) {
    thingsToDo()..
}

the else part is an addition to this structure to tell the compiler what to do if the condition is false

if (condition) {
    thingsToDo()..
} else {
    thingsToDoInOtherCase()..
}

you can combine those to form a else if which is when the first condition is false but you want to do another question before to decide what to do.

if (condition) {
    thingsToDo()..
} else if (condition2) {
    thingsToDoInTheSecondCase()..
}else {
    thingsToDoInOtherCase()..
}

if (numOptions == 1)
    return "if";
else if (numOptions > 2)
    return "else if";
else 
    return "else";

The syntax of if statement is

if(condition)
    something; // executed, when condition is true
else
    otherthing; // otherwise this part is executed

So, basically, else is a part of if construct (something and otherthing are often compound statements enclosed in {} and else part is, in fact, optional). And else if is a combination of two ifs, where otherthing is an if itself.

if(condition1)
    something;
else if(condition2)
    otherthing;
else
    totallydifferenthing;

Dead Simple Pseudo-Code Explanation:

/* If Example */
if(condition_is_true){
   do_this
}
now_do_this_regardless_of_whether_condition_was_true_or_false

/*  If-Else Example  */
if(condition_is_true){
    do_this
}else{
    do_this_if_condition_was_false
}
now_do_this_regardless_of_whether_condition_was_true_or_false

/* If-ElseIf-Else Example */
if(condition_is_true){
    do_this
}else if(different_condition_is_true){
    do_this_only_if_first_condition_was_false_and_different_condition_was_true
}else{
    do_this_only_if_neither_condition_was_true
}
now_do_this_regardless_of_whether_condition_was_true_or_false

I think it helps to think of the "else" as the word OTHERWISE.

so you would read it like this:

if (something is true)
{
   // do stuff
}
otherwise if (some other thing is true)
{
   // do some stuff
}
otherwise
{
   // do some other stuff :)
}

There's no "else if". You have the following:

if (condition)
    statement or block

Or:

if (condition)
    statement or block
else
    statement or block

In the first case, the statement or block is executed if the condition is true (different than 0). In the second case, if the condition is true, the first statement or block is executed, otherwise the second statement or block is executed.

So, when you write "else if", that's an "else statement", where the second statement is an if statement. You might have problems if you try to do this:

if (condition)
    if (condition)
        statement or block
else
    statement or block

The problem here being you want the "else" to refer to the first "if", but you are actually referring to the second one. You fix this by doing:

if (condition)
{
    if (condition)
        statement or block
} else
    statement or block

If-elseif-else can be written as a nested if-else. These are (logically speaking) equivalent:

if (A) 
{
    doA();
}
else if (B)
{
    doB();
}
else if (C)
{
    doC();
}
else
{
    doX();
}

is the same as:

if (A) 
{
    doA();
}
else
{
    if (B)
    {
        doB();
    }
    else
    {
         if (C)
         {
             doC();
         }
         else
         {
             doX();
         }
    }
}

The result is that ultimately only one of doA, doB, doC, or doX will be evaluated.


An if statement follows this sort of structure:

if (condition)
{
    // executed only if "condition" is true
}
else if (other condition)
{
    // executed only if "condition" was false and "other condition" is true
}
else
{
    // executed only if both "condition" and "other condition" were false
}

The if portion is the only block that is absolutely mandatory. else if allows you to say "ok, if the previous condition was not true, then if this condition is true...". The else says "if none of the conditions above were true..."

You can have multiple else if blocks, but only one if block and only one (or zero) else blocks.


The if statement uses the results of a logical expression to decide if one of two code blocks will be executed.

With this code

if (logical expression) {
    code block 1;
} else {
    code block 2;
}

if the logical expression is true, only the statements in code block 1 will be executed; if false, only the statements in code block 2.

In the case that there are multiple similar tests to be done (for instance if we are testing a number to be less than zero, equal to zero or more than zero) then the second test can be placed as the first statement of the else code block.

if (logical expression 1) {
    code block 1;
} else {
    if (logical expression 2) {
        code block 2;
    } else {
        code block 3;
    }
}

In this case, code block 1 is executed if logical expression 1 is true; code block 2 if logical expression 1 is false and logical expression 2 is true; code block 3 if both logical expressions are false.

Obviously this can be repeated with another if statement as the first statement of code block 3.

The else if statement is simply a reformatted version of this code.

if (logical expression 1) {
    code block 1;
} else if (logical expression 2) {
    code block 2;
} else {
    code block 3;
}