Selections: Theory

Variables and data types
  • Selection/Conditional Statements

    • Used to alter normal flow of control
    • Provides ability to decide order of execution
    • Selection constructs in C are
      • “if” statement
      • Conditional/Ternary operator statement (? : )
      • “switch” statement
  • “if” Statement

    • Allows us to establish decision-making in the programs
    • Allow programs to test certain condition and make decision about which code block to be executed
    • The if statement has two basic forms
      • Simple if-else
      • if-else if ladder
  • Simple if else statements

  • if-else if ladder

    • The condition is evaluated sequentially
      • From the top of the ladder and moving downwards
        if (condition){
            //one or more statements;
        }else if (condition) {
            //one or more statements;
            …
        }else {
            //one or more statements;
        }
  • Conditional/Ternary/? : Operator

    • This operator takes 3 expressions/operands
    • It is more efficient form for expressing simple if statement
    • General form
      • [variable = ] expr1 ? Expr2 : expr3
    • This simply states
      • if(expr1 is true) then expr2 else expr3
    • Where
      • expr2 is evaluated, if the value of expr1 is non-zero (true)
      • expr3 is evaluated, if the value of expr1 is zero (false)
  • Switch Statements

    • Can be used in place of if-else-if statements
    • Used in situations where the expression being evaluated results in multiple values
  • General form of Switch statement

    switch(expression){
        case item1:
            //one or more statements;
            break;
        case item2:
            //one or more statements;
            break;
        case itemn:
            //one or more statements;
            break;
        default:
            //one or more statements;
            break;
    }