C++ decision making structure Tccicomputercoaching.com

C++ Decision making structure allows you to make decision based on condition.

Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

C++ allows following statements as decision making structure:

If statement :

This includes only one if statement which contains one if condition, if it becomes true then true statement executes.

if( expression )

{

statement-inside;

}

statement-outside;

If-else statement :

This includes one condition, if it becomes true then executes true statement and if condition false, then false statement executes.

if( expression )

{

statement-block1;

}

else

{

statement-block2;

}

Nested if-else statement :

This contains if-else with another if-else. First if condition becomes true then second if condition checks, if it will true then its true statement executes otherwise its false statement executes.

if( expression )

{

if( expression1 )

{

statement-block1;

}

else

{

statement-block2;

}

}

else

{

statement-block3;

}

Else-if Ladder statement :

This contains more than one if conditions, which condition becomes true, its statement executes.

if(expression 1)

{

statement-block1;

}

else if(expression 2)

{

statement-block2;

}

else if(expression 3 )

{

statement-block3;

}

else

default-statement;

Example:

void main( )

{

int a;

cout<< “enter a number”;

cin>> a;

if( a%5==0 && a%8==0)

{

cout<< “divisible by both 5 and 8”;

}

else if( a%8==0 )

{

cout<< “divisible by 8”;

}

else if(a%5==0)

{

cout<< “divisible by 5”;

}

else

{

cout<< “divisible by none”;

}

getch();

}

Switch statement:

This is used when u have multiple choices and u have to choose one of them based on variable or expression value.