Page 204 - ComputerScience_Class_11
P. 204

Difference Between for Loop and while Loop
              The difference between for loop and while loop is given below:

                                        For Loop                                   While Loop
                       In the for loop, all the parameters (i.e., initialisation,  In the while loop, the parameters (i.e.,  initialisation,
                       test condition and increment or decrement) are in  test condition  and increment or decrement) are
                       the same line.                             written in separate lines.
                       This  loop  is  used  to  execute  a  set  of  statements  This  loop  is  used  to  execute  a  set  of  statements
                       repeatedly when the number of iterations is known.  repeatedly when the number of iterations is not known.
                       This loop is more concise and suitable for simple  This  loop  provide  more  flexibility  when  dealing  with
                       iteration.                                 complex loop conditions.

              Nested Loop
              When a loop is present inside the body of another loop, it is called a nested loop. It is also called loop inside loop.
              The syntax of a nested loop:
                  Outer loop structure
                  {
                      Inner loop structure
                      {
                          Statements inside inner loop
                      }
                      Statements inside outer loop
                  }
              Since all types of loops can have nested loop, the three types of nested loops are as follows:
              •  Nested for loop: The for loop inside another for loop is called a nested for loop.
                For example:

                Program 7     Write a Java program that uses nested for loops to print the following pattern:
                              2
                              4 4
                              6 6 6
                1       import java.util.Scanner;
                2       public class NestedForLoop {
                3           public static void main(String[] args) {
                4               int i;

                5               int j;
                6               for(i=1; i<=3; i++)
                7               {
                8                   for(j=1; j<=i; j++)
                9                   {
                10                      System.out.print(i*2);

                11                  }
                12                  System.out.println();
                13              }
                14          }
                15      }




                  202  Touchpad Computer Science (Ver. 3.0)-XI
   199   200   201   202   203   204   205   206   207   208   209