Page 246 - Computer Science Class 11 With Functions
P. 246

10.4 while Statement

        The while statement is used to execute a sequence of statements over and over again as long as the condition
        specified in the while statement is True. The sequence of statements that is executed repeatedly is called body of the
        while statement. The while statement has the following syntax:
        while test condition:
            Body of while loop
        [else:
            Statements]
        In the above syntax description:
          while is a keyword

          test condition is the expression that will evaluate to either True or False
           body of while  loop constitutes the statement(s) that will be executed if the test condition is True. These are
          determined through indentation. The first un-indented line marks the end of the loop.
           else (optional) is a keyword and the statements in else block (optional) will be executed after all the possible
          iterations of the while loop are executed.
        We first discuss the while  statement, ignoring the optional else clause. Fig 10.3 shows a flowchart that depicts
        the execution of such a while statement, Note that the Boolean expression (also called a conditional expression,
        test expression, or just a condition) in the while statement is evaluated before the body of the while statement
        is executed. If the Boolean expression yields False, the loop's body is skipped, and the execution of the while
        statement ends.  However, if the Boolean expression yields True, the body of the while statement is executed. On
        executing the loop's body, the Boolean expression is evaluated again. If the Boolean expression yields True, the

        loop's body is executed again. This process of evaluating the Boolean expression and executing the body of the while
        statement is repeated until the Boolean expression becomes False.


                                                           Enter while loop



                                                         Test      False
                                                      Expression




                                                           True


                                                    Body of while



                                                                Exit loop

                                                  Fig 10.3: while statement

        10.4.1 Summing the Digits of a Number

        Now we are ready to study an application of the while statement. Suppose we wish to find the sum of digits of a
        number.

           In Lines 22-23, we write a function sumofDigits(num) that accepts as input parameter the number num.
           On execution of Line 13, we ignore the sign of the number by taking its absolute value.


         244   Touchpad Computer Science-XI
   241   242   243   244   245   246   247   248   249   250   251