Tuesday, May 12, 2009

Nested If-else Statements

Nested if-else statements
When a series of if –else statements are occurred in a program, we can write an entire if-else statement in another if-else statement called nesting. And the statement is called nested if.

Syntax:

if(condition 1)
{
statements 1;
}
else if(condition 2)
{
statements 2;
}

else if(condition 3)
{
statements 3;
}
else
{
statements 4;
}

statements 5;

If Condition 1 is true Statements 1 and Statements 5 will be executed. If condition 1 is false Condition 2 (Statements 2) and Statements 5 will be executed. If Condition 1 and Condition 2 is false, then Condition 3 (Statement 3) and Statements 5 will be executed. If Condition 1, Condition 2 and Condition 3 is false, then process goes to else part and Statements 4 and Statements 5 will be executed.

Note: Statements 5 will be executed


Note that the third if-else statements is nested in the second else statement and second if-else statements is nested in the first else statements. If the condition in the first “if” statement is false, then the condition in the second if statement will be executed, if the second “if” statement is false, then the condition in the third “if” statement will be executed. If it is false then the final else statement is executed.



Example:

if (a>10)
{
cout<<”A Value is greater than 10”;
}
Else if(a<10)
{
cout<<”A value is less than 10”;

}
Else if(a==10)
{
cout<<”A value is :” << a;
}
Cout<<”A= “ <



Similarly, we can construct any number of if-else statements in nested fashion, that is called if-else ladder.
If you want to test more than one condition in if statement the logical operator are used as specified below. These are used to combine the results of two or more conditions.

Operator Meaning
&& Logical And
|| Logical Or
! Logical Not


Example:

Header files
Class biggest
{
Int a,b,c;
Public:
Void get();
Void put();

};
void biggest::get()
{
cout<<”Enter the Value of A , B and C:”;
cin>> a >> b >> c;
}
void biggest::put()
{
if(a>b)&&(a>c)
{
cout<<”A is biggest number”;
}
else if(b>c)
{
cout<<”B is biggest Number”;
}
else
{
cout<<"C is Biggest Number";
}
cout<<”A = “ <gamma waves

Google Search