Decision Making

Decision making statement statements is also called selection statement. That is depending on the condition block need to be executed or not which is decided by condition. If the condition is "true" statement block will be executed, if condition is "false" then statement block will not be executed.

There are Four types of decision making statement-

(1)-if statement

(2)-if else statement

(3)-nested if statement

(4)-switch statement

 

if statement

  • You can use if statement to check a specified condition.
  • It performs a course of action if the condition is true otherwise,the action is ignored.
  • An if statement consists of a boolean expression followed by one or more statements.

Syntax

if(condition){
 statement(s)
}

Note-You need not apply curly brackets if a single statement is to be performed for true condition.

Flow Diagram

Flow Diagram of if statement

if else statement

  • It is a logical situation when either of the two actions are to be performed depending upon certain condition.
  • If the condition is true it performs one set of statements otherwise perform another set of statement.

Syntax

if(condition)
{
statement(s);
}
else
{
statement(s);
}

Flow Diagram

Flow Diagram of if else statement

Nested if (with if-else-if)statement

  • When an if statement is placed within another if,it is known as nested if statement.
  • It can be done by using if-else-if structure.

Syntax

if(condition 1)
{
if(condition 2)
Statement 1
else
Statement 2
}
else{
if(condition 3)
Statement 3
else
Statement 4
}

Explanation-In the Syntax shown above,first of all condition 1 is checked,if it is true then it further checks conditon 2 and performs action statement 1 or statement 2 accordingly.

In case condition 1 is false,the control enters else part and further checks condition 3.Statement 3 and statement 4 are executed accordingly to the result of condition 3.

Flow Diagram

Flow Diagram of nested if else statement
Fig- Flow Diagram of nested if...else statement

Switch Statement

  • This is a branching control statement,where the end of each case acts as an exit from the switch statement.
  • In Switch Statement,a number of statement are put together with different cases.
  • The Switch statement works as a jumping statement,where the control is transferred to a specific case as per the given switch value.
  • Each case ends with a break statement,which acts as a terminator and the control comes out of the blocks.
  • The default statement is executed only when the switch value doesn't match with the case.If doesn't require any usage of break as it is the last segment of the switch case structure.

Syntax

switch(expression/variable)
{
case value:
//statement(s);
//number of cases
break;//optional
default//optional
//statement
}  

Flow Diagram

Flow Diagram of switch statement
Fig- Flow Diagram of Switch Statement