Page 241 - IT-802_class_12
P. 241

More about Loop
            1.  If there is only one statement in the body of the loop, the set of curly braces enclosing the body can be omitted.

              For example,

              for ( int count = 5; count < 10; count++)
              System.out.println (count);
            2.   You can use multiple items in the initialization and the updating part of the loop by separating them with the
              comma operator.

              For example,
              for ( x = 0, y = 10; x < 10; x++, y--)
              System.out.println(“x = “ + x + “y = “ + y);
            3.  Do remember to use indentation to align the body of the loop, it will make it easier for you to debug your code.

            Common Coding Errors: The for Loop
            1.  Initial value is greater than the limit value and the loop increment is positive.
              For example,

              for ( int count = 5; count <= 1; count++)
              In this case, body of the loop will never be executed.
            2.  Initial value is lesser than the limit value and the loop increment is negative.
              For example,

              for ( int count = 1; count >= 5; count --)
              In this case also, body of the loop will never be executed.
            3.  Placing a semicolon at the end of a for statement:

              for ( int count = 1; count <= 5; count++);
              {
              //body of loop
              }
               This has the effect of defining the body of the loop to be empty. The statements within the curly braces will be
              executed only once (after the for loop terminates) and not as many times as expected.
            4.   Executing the loop either more or less times than the desired number of times. For example, the following loop
              iterates 4 times and not the intended 5 times because it exits when count = 5.
              for ( int count = 1; count < 5; count ++)
              The correct way to loop five times would be to test for count <= 5.

              Such errors are known as off by one error.
            5.  Using a loop index (declared within the loop) outside the loop.

              for ( int count = 1; count < 5; count ++)
              {
              System.out.println(count);
              }

              System.out.println(count); //error!!
            The scope of the variable count is only within the body of the loop. It is not visible outside the loop.



                                                                               Fundamentals of Java Programming  239
   236   237   238   239   240   241   242   243   244   245   246