Thursday, 23 July 2015

If else : The decision making continues!

In this post we continue if else where we left off in the previous post.

Nested if: This means that one if (or if-else) is present inside another if or else's body. For instance,

if(i>2)
{
if(i%2==0)
{
cout<<"i is greater than 2 and divisible by 2";
}
}
else
{
cout<<"i is less than 2";
}

If statements can be nested more than once, and can be present inside else too. For instance,

if(value>10)
{
if(value>100)
{
if(value>1000)
{
cout<<"Value is too large!";
}

else
{
if(value>500)
cout<<"Value is large but not too large!";
}
}
}

Dangling else: If more than one if statement is present in the program, the else statement goes with the preceding unmatched if statement. This means,

if(i>2)
if(i>5)
//Some code here
else
//Some code here

In the above example, the statement below else are executed if i is not greater than 5. If we want to override (or change) this, we can use braces. So,

int i=10;

if(i>2)
{
if(i>5)
//Some code here
}
else
//Some code here

Now, the else statements will be executed if i is less than 5.

If-else-if ladder: When code takes the following form, i.e., if statements nested within else's block.

if(condition1)
//Statement1
else
{
if(condition2)
//Statement2
else
{
if(condition3)
//Statement3
else
//Statement4
}
}

In the above code, only one of the four statements (Statement1,Statement2,Statement3 or Statement4) will be executed, depending upon which condition is satisfied FIRST. This means that if condition1 is true, Statement1 will be executed and control will not go into the else lock. Therefore, in such a case Statement3 will NOT be executed even if condition3 is true.

To make it less tedious, it is generally written as:

if(condition1)
//Statement1
else if(condition2)
//Statement2
else if(condition3)
//Statement3
else
//Statement4

Both the codes are equivalent.

That's it for now. Post your queries in the comments section!

No comments:

Post a Comment