Loops: Theory

Variables and data types
  • Introduction to loops

    Without loops
    With loops
  • What is a loop?

    • Section of code in a program
      • which is executed repeatedly,
      • until a specific condition is satisfied
    • There are three types of loop structures
      • “for” loop
      • “while” loop
      • “do…while” loop
  • Loops flowchart

  • General form of a for loop

    • General form
      for (expression1; expression2; expression3 ){
          // one or more statements;
      }
    • Expression1
      • Initializes counter/index variable
      • Is usually an assignment statement
      • Is executed once at the beginning (only once)
    • Expression 2
      • Sets terminating condition
      • Is evaluated at the beginning of every iteration
      • If true statements inside the loop is executed; if false exit the loop
    • Expression 3
      • Is the loop variant/modifier (increment/decrement)
      • Is evaluated at the end of every iteration
  • The “while” loop

    • Syntax
      while (condition is true){
          //one or more statements;
      }
    • It’s entry controlled loop statement
    • The condition is true, the loop body is executed
    • Otherwise, the loop will finish
  • The “do-while” loop

    • Syntax
      do{
          //one or more statements;
      }while (condition is true);
    • Program will always execute the loop body first
    • The body is always executed at least once
    • At the end of every loop, condition is evaluated
    • If it’s true, the loop continues
    • If it’s false, the loop finishes
    • The do-while statement must be terminated with ‘;’