Page 72 - Digicode_AI_class_7
P. 72

Different Types of Loops

            Loop runs a statement or group of statements multiple times till the given condition is true. There
            are different types loops. Although they perform the same task, but their working is different. Let us
            take a look at the types of loop.

            Different types of loops are:
            1. While Loop          2. For Loop          3. Nested Loop

            While Loop/Conditional Loop
            While Loop executes a statement or group of statements till a given condition is true. Once the
            condition is false, the loop is terminated.
            Example: To print number from 1 to 10.
            Condition: Write numbers from 1 to 10.

            Decision: Have we reached number 0.
            Pseudocode:
            Program Start
            set a to 0

            while a is less than 10
                   increase the value of a by 1
                   display a
            Program End
            Example: To print a statement five times by using a while loop.
            Condition: Till the time the test expression remains true, the body of the while loop will run.
            Decision: Have we printed the statement five times or not?
            Pseudocode:
            Program Start
            set a to 0

            while a is less than 5
                increase the value of a by 1
                display Hello World
            Program End
            Example: To print number from 5 to 1.
            Condition:  Till  the  time  the  test  expression  remains  true,  the  body  of the  while  loop  printing
            statement will run and once the condition is false the loop will stop executing.
            Decision: Have we printed 1?
            Pseudocode:
            Program Start
            set a to 0
            while a is equal to 1
                display the value of a
                decrease the value of a by 1

            Program End

                 70    DigiCode AI-VII
   67   68   69   70   71   72   73   74   75   76   77