Search This Blog

If you like any posts in this blog then click this icon which is present under the post

Saturday, 23 July 2011

Nested if .... else Statement


                This statement is formed by joining if ….. else statements either in the block or in the else block or both. The general form is

if(test condition-1)
{
    if(test condition-2)
    {
    Statement block-1;
    }
    else
    {
    Statement block-2;

    }
}
else
    {
    Statement block-3;
    }
next statement;

When this statement is executed, the computer first evaluates the value of test condition-1. If it is false control will be transferred to statement block-3. If it is true test condition-2 is evaluated. If it is true statement block-1 is executed and control is transferred to next statement else statement block-2 is executed and control is next statement.
  
Rules

1.       The brackets around the test condition are must.
2.       The test conditions must be a relational or logical expression.
3.       Statement blocks are called body of the if………else statement. It can contain one or more statements.
4.       The opening statement and closing brackets {} are must if the statement blocks contain more than one statement. Else optional
5.       No statements other than the statements in the statement blocks are allowed between if ….. else.
6.       Each else must match with the nearest if preceding it, which has not already been matched by an else.

Flow diagram


Example

Program to find the biggest of 3 numbers

Class Large
{
public static void main(String args[])
                {
                                int a=20;
int b=40;
int c=80;
if(a>b)
{
                if(a>c)
                System.out.println(“big=”+a);
                else
                System.out.println(“big=”+c);
                else
                                                {
                                                                if(b>c)
                                System.out.println(“big=”+b);
                                else
System.out.println(“big=”+c);
                                                }
}
                }
}

No comments:

Post a Comment

Followers