Decision making statements

if-else ladder:


if-else ladder is used when you want to check multiple conditions for one purpose.


advantage of using an if-else ladder is in the entire flow ladder if one condition becomes true then the flow will exit the ladder and flow will pass to the next statement to be executed


syntax:


if(condition){

statements to be executed when this particular condition becomes true

}

else if ( condition){

statements to be executed when this particular condition becomes true

}

else if ( condition){

statements to be executed when this particular condition becomes true

}

.

.

.

else{

statements to be executed when above else if condition becomes false.

}


Again here notice that else statement is only executed when last else if statements condition becomes false, not for the entire ladder.


Example:


switch case statement:


if we want to check multiple or one condition for only one particular value for each time then we can also use the switch case conditional statement.


here basically we compare one particular value(constant) given in switch with other value in case when the value provided in the switch statement and case statement become the same then the statement after that particular case is executed.


syntax:


switch(n){


case 1:

statements to be executed when value n is equal to 1, else the condition becomes false.

break;


case 2:

statements to be executed when value n is equal to 2, else the condition becomes false.

break;

.

.

.

case m:

statements to be executed when value n is equal to m, else the condition becomes false.

break;


default:

statements to be executed when the value of n doesn't match with any case.

}


Now here break; statement plays an important role if we don't use break statement or say we missed up to write break statement then what happens is all case after that case become true and they all executed one by one until the next break statement not appears.


some points to be remembered while using a switch statement.



  • Not two case values can be the same, it gives a compile error.

  • default statement is not compulsory, it can be omitted. we can place the default statement anywhere inside the switch block.

  • switch statements can be nested.

  • the expression provided in the switch should result in constant value.

  • expression used in switch case it must be an integer type only. not any other data types value is allowed.

  •  break statement is optional, if we omitted then next case statements are executed and this process is continued until a break is reached.


let's go through the example of it, Actually what happens when we missed up the break statement, and also notice that it is also useful too in many cases.