Page 199 - CA_Blue( J )_Class9
P. 199

// job performed by the body of the loop
                        increment or decrement;
                    }
                       Note:  In a while loop, if you don't include an increment or decrement step (or otherwise modify the
                       loop condition), the loop will not terminate, leading to an infinite loop.



                  Program 3      Print sum of all the digits of a number.


                   1      class while_sumdigits
                   2      {

                   3          public static void main()
                   4          {

                   5              int n=1436,r,s=0,t;
                   6              t=n;

                   7              while(t>0)
                   8              {

                   9                  r=t%10;
                  10                  s=s+r;
                  11                  t=t/10;

                  12              }

                  13              System.out.println("Sum of "+n+" is : "+s);
                  14          }
                  15      }

                 You will get the following output:











                                                           Dry Run & Output

                        Step Number             n                  t                 r                  s

                             1                1436              1436>0               6                  6
                             2                                  143>0                3                  9
                             3                                  14>0                 4                 13

                             4                                  1>0                  1                 14
                             5                                  0>0




                                                                                       Iterative Constructs in Java  197
   194   195   196   197   198   199   200   201   202   203   204