coderz.py

Keep Coding Keep Cheering!

if-else ladder & nested if block

method overloading and method overriding
if-else ladder:

The if-else-if ladder statement is used to test multiple conditions in Java. It’s used to test a single condition from a set of statements.

When there are multiple conditions to execute, the if-else-if ladder makes the code easy to understand and work with.

Syntax:

	
if(condition1)
{  
	//code for if condition1 is true  
}
else if(condition2)
{  
	//code for if condition2 is true  
}  
else if(condition3)
{  
	//code for if condition3 is true  
}  
...  
else
{  
	//code for all the false conditions   
}  
	
If Else If Block data flow diagram:
if else ladder
Example:

import java.util.Scanner;
public class Demo1 {  
public static void main(String[] args) 
	{  
	Scanner sc= new Scanner(System.in);
	float  percent;
	System.out.println("Enter number:");
	percent =sc.nextFloat();
	if(percent >95 )
		{  
		System.out.print(" PASS - A+");  
		
		}  
		else if(percent<=85 && percent >75){
		    	System.out.print(" PASS - A");  
		}
			else if(percent<=75 && percent >65){
		    	System.out.print(" PASS - B");  
		}
			else if(percent<=65 && percent >55){
		    	System.out.print(" PASS - C");  
		}
			else if(percent<=45 && percent >35){
		    	System.out.print(" PASS - D");  
		}
			else if( percent <35){
		    	System.out.print(" FAIL - F");  
		}
	}  
}  
Output:

Various inputs:

Enter number:78
PASS - A

Enter number:97
PASS - A+

Enter number:
31
FAIL - F
Nested if Block:

A nested if statement is an if inside another if statement. In this case, one if block is placed inside another if block, and only the inner block is executed if the outer block is true.

Syntax:

	
if(condition)
{    
     		//statement
     if(condition)
{  
             //statement 
    }    
}  
	
Nested If Block data flow diagram:
if else ladder
Example:
import java.util.Scanner;
public class IfDemo1 {  
public static void main(String[] args) 
	{  Scanner sc=new Scanner(System.in);
	    char gender;
	    	float  age;  
	    System.out.println("enter gender and age: ");
        gender=sc.next().charAt(0);
     age=sc.nextFloat();
	if(gender == 'M')
		{ 
		    if(age>=20)
		System.out.print("Can be married legally");  
		   else
		   	System.out.print("Cannot be married ");  
		   
		}  
		else if(gender=='F'){
		     if(age>=20)
		System.out.print("Can be married legally");  
		   else
		   	System.out.print("Cannot be married ");  
		}
		else{
		    	System.out.print("Invalid ");
		}
		
	}  
}  
	
Output:
enter gender and age: 
F 32
Can be married legally

Note: also read about the Selection Statement

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Comment

Your email address will not be published. Required fields are marked *

Advertisement