Page 61 - Modular_V2.0_C++_Flikpbook
P. 61

6

                                                                                                       LOOPS










                                Your Aim


                                to learn about:
                                        The for Loop                    The while Loop
                                         The do-while Loop                Nested Loop
                                         Infinite Loop
                                          Difference Between while and do-while Loops
                                           Jump Statements                       More Solved Programs



                 Sometimes, we need to repeat a task multiple times or until a condition is met. In C++, statements
                 used to repeat instructions are called looping statements or iterative statements. Loops help
                 us avoid writing the same code again and again, making programs shorter and more efficient.
                 Loops allow you to repeat a section of your program for a certain number of times. The repetition
                 continues until a condition is true. When the condition becomes false, the loop ends and control
                 passes to the statements following the loop. C++ provides three types of loops: for loop, while

                 loop and do-while loop.

                    THE FOR LOOP

                 The for loop executes a simple or compound statements for a fixed number of times or until a
                 condition becomes false. The syntax of the for statement is given below:

                      for(initialisation; condition; update)
                      {

                          statements;
                      }

                 Components of a for loop:
                    initialisation is a method to assign value to the variable(s) starting the loop (called loop
                    variables). Once the initialisation process is completed, it’s never evaluated again.

                    condition is a conditional expression to decide whether to enter the loop or not.
                    update is a variable to change the value(s) of loop variable(s) after each iteration. Iteration is
                    the process of running a loop one time.


                                                                                                                  59
                                                                                                         Loops
   56   57   58   59   60   61   62   63   64   65   66