Conditonal Statements
Conditional Statements
By using the Conditional Statements we can easily control the flow of the program.
- if statement
- if - else statement
- Nested if statement
- if else if ladder
- switch statement
1) if statement:
- It executes the set of code / block when the given condition is true.
- It doesn't execute the block when the given condition is false.
Syntax:
if(condition){
//statements to be execute when the given condition is true
}
2) if - else statement:
- It is used to execute the different block of code alternatively.
- It is similar to if statement.
- If the condition is matched/true then if block statements will executes.
- If the condition is not matched/false then else block statements will executes.
- else is a extension of if statement.
- Without if we cannot use else statement.
Syntax:
if(condition){
//statements when condition is true
}else{
//statements when condition is false
}
3) Nested if statement:
- It is used to check the 2 or more if conditions.
- Here we write if / if-else statements inside a another if / if-else statement.
Syntax:
if(condition1){
//statements executes when condition1 is true
if(condition2){
//statements executes when both condition1and2 are true
if(conditon3){
//statements executes when condition1,2and3 are true
}
}else{
//statements executes when condition2 is false
}
}
4) if-else Ladder:
- It is used to check the 2 or more if -else conditions alternatively.
- When any one of the if condition is satisfied then remaining conditions of if block will not be checked even though there is a matching if block condition is available.
- When there is no if block condition is true then it executes the else block.
Syntax:
if(condition1){
//executes when condition1 is true
}else if(condition2){
//executes when condition2 is true and condition1 is false
}else if(condition3){
//executes only when conditon3 is true and conditon 1,2 is false
}else{
//executes when all conditions are false
}
5) switch statement:
- It executes only when given expression is exactly equal to case values.
- When there is no matching case is available then it executes default case.
- When there is a matching case available it executes all cases statements from the matching case.
- To over come the above problem we use break keyword at the end of each case statement.
Syntax:
switch(expression){
case value1:
statements;
break;
case value2:
statements;
break;
case value3:
statements;
break;
//upto n cases
default:
statements;
}
Comments
Post a Comment