tags:

views:

877

answers:

13

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?

+18  A: 

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.

Adam Robinson
Just to be clear for the OP: one and only one of the statement blocks will be executed during a pass through a group of if/else statements. So if both `condition` and `other condition` are true, only condition's code will be executed.
fbrereto
@fbrerto: Good point, thanks!
Adam Robinson
ah so if you have multiple choices inside an if, then you use the else if?
HollerTrain
@unknown (by the way, you should register) That's correct. There are other flow control statements like "case" that can also be used for scenarios like this. Picking the right one is something you'll learn.
Adam Robinson
lol yes i should. yes we'll be working with cases next week (which looks to be an easier method than if/else?)
HollerTrain
FYI: There's really no such thing as an "else if". It's just an else statement which contains an if statement.
Pod
@pod: semantically you're correct, but it's still an important idea to learn about.
Adam Robinson
@Pod: I agree with you. I think it goes a long way towards clearing up confusion about how they work to realize that "else if" is a compound structure, not its own thing. Though Adam is right that they are used as a single unit so much they are usually though of as a unit.
rmeador
+9  A: 

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();
}
Malaxeur
+1 for using real-world concepts rather than just placeholders like `condition` or `a`, `b`, etc.
Grant Wagner
+1 for real-world concepts. How would you define the following, as this is where I am running into issues:if it's sunny go outside. if it's sunny go to park. if it's sunny go to the store. if it's sunny go to the discoteck.if it's stormy go downstairs. if it's stormy go in the living room. if it's stormy go into the parlor. if it's stormy go into your bedroom.
HollerTrain
the multiple ifs inside the main if is where i am having trouble
HollerTrain
Ifs within ifs can be rewritten using 'ands'For example, if you want to write 'if it's sunny and warm, go outside' and 'if it's sunny and cold, do nothing' you can write it either as:if (sunny) { if (warm) { goOutside(); } else if (cold) { doNothing(); }}ORif (sunny }else if (sunny }I'll edit and add these examples in.
Malaxeur
that most definitely didn't format properly. please see the answer's edit section instead :P
Malaxeur
A: 

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
}
Jeff Pinkston
A: 

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;
Michael Krelin - hacker
+13  A: 

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.

Mark Rushakoff
I'm glad someone pointed out `else if` isn't a keyword, and just a formatted combination of `else` and `if`
GMan
Agreed GMan, this isn't Python, Perl, VB etc. There's only if and else here.
Pod
+6  A: 

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
Daniel
It is precisely this problem, known as the "dangling ELSE" problem and first seen in PASCAL (or possibly ALGOL), long before C was developed, that caused Jean Ichbiah and his team to adopt the fully-bracketed style for control structures in Ada.
John R. Strohm
+1 For there is no "else if" statement. There's an `if` statement comprised of a statement when true and [optionally] a statement when false. The developer can take advantage of the statement when false to check a new condition, and since this is an ubiquitous case it's become known as simply the "else if".
280Z28
A: 

Hi,

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()..
}
4NDR01D3
in the last ex are u missing a } to close out the else if?
HollerTrain
A: 
if (numOptions == 1)
    return "if";
else if (numOptions > 2)
    return "else if";
else 
    return "else";
AShelly
I think you meant `numOptions == 1`
Nick Meyer
I'm so embarrassed...
AShelly
A: 

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;
}
David Harris
+1  A: 

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

Clifford
+3  A: 

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
JStriedl
what if you have additional conditions inside the <code>else if(different_condition_is_true){ do_this_only_if_first_condition_was_false_and_different_condition_was_true}</code>I need to allow?
HollerTrain
do_this_only_if_first_condition_was_false_and_different_condition_was_true could be replaced with whatever you want, if replaced with a nested if(condition){do_this} it will behave accordingly.
JStriedl
A: 

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 :)
}
Alex Baranosky
+1  A: 
**IF** you are confused
 read the c# spec
**ELSE IF** you are kind of confused
 read some books
**ELSE**
 everything should be OK.

:)

Ray Booysen