It is possible to place an if loop inside the body of another if or else. Such an arrangements of loop is known as loop ladder. For example consider the following set of code.
if (condition-1) // outer if loop
{
if(condition-2) // inner if loop
{
statements;
}
else
{
statements;
}
statements;
}
else
{
if (condition-3) // inner if loop
{
statements;
}
}
You can see that the execution of the inner loop depends on the outer loop condition. Consider the following example for more details.
import java.io.*;
class LoopLadderDemo
{
public static void main(String args[]) throws IOException
{
int num1,num2,num3;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter first number :");
num1 = Integer.parseInt(br.readLine());
System.out.println("Enter second number :");
num2 = Integer.parseInt(br.readLine());
System.out.println("Enter third number :");
num3 = Integer.parseInt(br.readLine());
if(num1>num2)
{
if(num1>num3)
{
System.out.println("First number is the large number");
}
}
else if (num2>num1)
{
if(num2>num3)
{
System.out.println("Second number is the large number");
}
}
else if (num3>num1)
{
if(num3>num1)
{
System.out.println("Third number is the large number");
}
}
else
{
System.out.println("All the numbers are same");
}
}
}
Output:
if (condition-1) // outer if loop
{
if(condition-2) // inner if loop
{
statements;
}
else
{
statements;
}
statements;
}
else
{
if (condition-3) // inner if loop
{
statements;
}
}
You can see that the execution of the inner loop depends on the outer loop condition. Consider the following example for more details.
import java.io.*;
class LoopLadderDemo
{
public static void main(String args[]) throws IOException
{
int num1,num2,num3;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter first number :");
num1 = Integer.parseInt(br.readLine());
System.out.println("Enter second number :");
num2 = Integer.parseInt(br.readLine());
System.out.println("Enter third number :");
num3 = Integer.parseInt(br.readLine());
if(num1>num2)
{
if(num1>num3)
{
System.out.println("First number is the large number");
}
}
else if (num2>num1)
{
if(num2>num3)
{
System.out.println("Second number is the large number");
}
}
else if (num3>num1)
{
if(num3>num1)
{
System.out.println("Third number is the large number");
}
}
else
{
System.out.println("All the numbers are same");
}
}
}
Output:
Comments
Post a Comment