/* related posts with thumb nails */

### Decision making and branching structures:

Branching structures include conditional control structures and switch.

1. Conditional control structure (Branching):

a) if:

Syntax:

if (condition)

{

statements

}

Explanation:

If structure is also called as conditional statement. In If, statements get executed only when the condition is true. It omits the condition based statements when the condition is false. Braces are not necessary if only one statement is related to the condition.

Example:

if ( x > 0 )

System.out.println(“positive”);

b) if else:

Syntax:

if (condition)

{

Statements

}

else

{

Statements

}

Explanation:

Statements in if block get executed only when the condition is true and statements in else block get executed only when the condition is false.

Example:

if ( x > y )

System.out.println( “x is big”);

else

System.out.println( “y is big or equal ”);

c) if else if:

Syntax:

if (condition1)

{

Statements

}

else if (condition2)

{

Statements

}

else if (condition3)

{

Statements

}

.

.

.

else

{

statements

}

Explanation:

Statements get executed in loops only when the corresponding conditions are true. Statements in the final else block get executed when all other conditions are false. The control checks a condition only when all the afore-mentioned conditions are false.

Example:

if ( x > 0 )

System.out.println( “positive”);

else if ( x < 0)

System.out.println(“negative ”);

else

System.out.println( “zero”);

d) nested if:

Syntax:

if (condition1)

{

if ( condition2)

{

Statements

}

}

Explanation:

Writing if in another if is nested if. Inner if is processed only when outer if’s condition is true. Hence, statements in inner-if get executed only when condition1 and condition2 are true.

Example:

if ( a > b )

{

if (a>c)

System.out.println( “ a is the biggest”);

}

e) switch:

Syntax:

switch(variable)

{

case constant1: statment1

break;

case constant2: statement2

break;

.

.

default: statements

break;

}

Explanation:

switch is similar to if else if. Statement 1 gets executed when the variable is equal to constant1 and so on. Control comes to “default” portion when all the cases (constants), which have been mentioned do not match with the value of the variable. Here break and default are optional. When there is no break for a case it continues till it encounters break or the end of the switch loop.

Example:

k=x-y;

switch(k)

{

case 0: System.out.println( “ x and y are equal”);

break;

default: System.out.println( “ x and y are not equal”);

break;

}

Related Topics: