Algo & Prog Selection

Today we’re gonna talk about Selections in Algorithms & Programmings

 

Selection Definition

in an algorithm implementation, an instruction or block of instructions may be executed (or not) with certain predetermined condition

Syntax:

–if

–if-else

–switch-case

IF

Syntax :

if (boolean expression) statement;

or

if (boolean expression) {

     statement1;

     statement2;

  ……

}

If boolean expression resulting in True, then a statement or some statements will be executed.

Selection: IF-ELSE

Syntax :

if (boolean expression) statement1;

else statement2;

or

if (boolean expression){

   statement1;

   statement2;

   ……

}

else {

   statement3;

   statement4;

   …

}

If boolean expression resulting in TRUE, then statement1 or  block statement1 will be executed, if FALSE then statement2 or block statement2 be executed.

NESTED-IF

  • Nested selection occurs when the word IF appears more than once within IF statement.

Syntax :

if (boolean expression) statement1;

if (boolean expression) statement2;

if (boolean expression) statement3;

or

if (boolean expression) statement1;

else

  if (boolean expression) statement2;

  else

  if (boolean expression) statement3;

SWITCH-CASE

Switch-Case Operation

This statement is used in exchange of IF-ELSE, when if-else nested number of level is enormous and difficult to read

Syntax:

switch (expression) {

  case constant1 : statements1; break;

  .

  .

  case constant2 : statements2; break;

  default : statements;

}

?: Operator

The operator ? : is similar to the IF statement, but it returns a value

Syntax:

  condition ? then-expression : else-expression

Using this operator, you can rewrite

if(a > b)

max_value = a;

else

max_value = b;

as

max_value = (a > b) ? a : b;

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.