Lesson 06: Loops

Loops in C/C++ come into use when we need to execute a block of statements repeatedly.

There are mainly two types of loops:

  • Entry Controlled loops: In this loop type, the test condition is tested before entering the loop body. For Loop and While Loop are entry-controlled loops.
  • Exit Controlled Loops: In this loop type, the test condition is tested or evaluated at the end of the loop body. Therefore, the loop body will execute at least once, irrespective of whether the test condition is true or false. The do-while loop is a controlled loop.

F1 1 Loops
Figure 1: Loops

Summary

  • Use for loop when the number of iterations is known beforehand, i.e. the number of times the loop body is needed to be executed is known.
  • Use while loops where the exact number of iterations is not known, but the loop termination condition is known.
  • Use do-while loop if the code needs to be executed at least once like in Menu-driven programs


Questions

  1. Binary and Hexadecimal: Input an unsigned 8-bit integer (uint8_t) and display its binary and hexadecimal value on the screen. (Using shifter and bitmask to get all digits from left to right).
  2. Use for loops to construct a program that displays the following pattern on the screen:
    1. X
      XX
      XXX
      XXXX
      XXXXX

    1.     X
         XX
      XXX
      XXXX
      XXXXX

    1.     X
         XXX
      XXXXX
      XXXXXXX
      XXXXXXXXX

    1. XXXXXXXXX
      XXXXXXX
      XXXXX
         XXX
          X

    1.     X
         XXX
      XXXXX
      XXXXXXX
      XXXXXXXXX
      XXXXXXX
      XXXXX
         XXX
          X

    1.     X
         XX
      XXX
      XXXX
      XXXXX
      XXXX
      XXX
      XX
      X

    For (b), (c), (d), (e), and (f), one way to do this is to nest two inner loops, one to print spaces and one to print Xs, inside an outer loop that steps down the screen from line to line.
© 2024 Air Supply Information Center (Air Supply BBS)