Selection Statements

Selection Statements

  • Programming is all about solving problems.

  • It’s basically useless to develop a program with no purpose; thus programming is all about coming up with a solution to a problem.

  • In programming, the series of steps taken in a particular order to solve a problem are known as an algorithm.

  • The structure theorem explains that we express algorithms to solve problems using a combination of the following three elements:

  1. Sequence – order imposed upon steps of an algorithm

  2. Selection – coming up with a decision based upon some condition

  3. Repetition – repeating one or steps of the algorithm a certain number of times until some condition is met.

Selection Control Structure

  • For better functionality, programs are supposed to be able to make decisions.

  • Selection Statements are used when making conditions about what task needs to be performed – based upon a certain condition.

  • It allows the program to choose any one path from different sets of paths of execution based upon the outcome of an expression or state of a variable.

  • In C, there are two selection statements: switch and if.

If Statement

  • The statement inside the if statement block is executed only when the condition is true

  • if syntax:

if (condition){
statement;
}
  • if else syntax:
if (condition){
statement;
}
else{
statement;
}
  • nested if else syntax:
if (condition){
    if (condition){
      statement;
    }
    else{
    statement;
    }
}
else{
    if (condition){
    statement;
    }
    else{
      condition;
      }
}
  • if-else-if syntax:
if (condition_1)
{
statement;
}
else if (condition_2){
statement;
}
else if (condition_3){
statement;
}
else{
statement;
}

Switch Statement

  • It is an alternative to the if-else-if statement which allows us to execute multiple operations for the different possible values of a single variable.

  • switch can be used to select between alternative options just like the if else

NB: the switch construct is similar to the nested if-else but is more appropriate when different tasks must be selected – best for menus.

  • switch syntax:
switch (expression)
{
case 1 :
    statement;
    break;
case 2:
    statement;
    break;
default:
    break statement;
    break;
}

Limitations of switch statement

  1. Can only be used for integers and characters only.

  2. It does not support ranges.

  3. Suited for a limited number of options.

  4. Operators cannot be used between switch statements.