❮ Previous Next ❯

Nested if statement:

When an if statement is present inside another if statement, called nested if statement.

//For example,
if(n%2==0)
{
if(n<40)
{
System.out.println("have got an even number<40");
}
}
else
System.out.println("have got an odd number");

Now the message for an even value is displayed only if the value of number is also less than 40. There are three possible outcomes from this code fragment. If number is even and less than 40, you will see the message to that effect, if number is even and is not less than 40, there will be no output, and finally if number is odd, a message will be displayed.
If-else-if Ladder: It is based upon a sequence of nested ifs. The general form of the if-else-if ladder is :

if(condition)
statement ;
else if(condition)
statement ;
else if(condition)
statement ;
-----
-----
else
statement ;

The if statements are executed from the top down. Once one of the condition is true, the statement associated with that if is executed, and rest of the ladder is neglected. If none of the conditions is true, then the final else statement will be executed.
If there is no final else and all other conditions are false, then no action will take place.
Let's see a program to demonstrate if-else-if ladder:

import java.util.Scanner;
class NestedIfDemo
{
public static void main(String[] args)
{
int m1,m2,m3,m4;
double avg;
Scanner s=new Scanner(System.in);
System.out.println("enter the marks");
m1=s.nextInt();
m2=s.nextInt();
m3=s.nextInt();
m4=s.nextInt();
avg=(m1+m2+m3+m4)/4;
if(avg>60)
System.out.println("1st division");
else if((avg>=40)&&(avg<60))
System.out.println("2nd division");
else
if((avg>=30)&&(avg<40))
System.out.println("3rd division");
else
System.out.println("fail");
}
}
//Output

enter the marks
62
35
45
52
2nd division

❮ Previous Next ❯



  Tutorials

Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Bhubaneswar-751013
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved