Page 376 - computer science (868) class 11
P. 376

Program 8     Design a class Pattern which will accept number of lines as n and print the pattern. If n = 5
                              then the pattern is:
                              12345
                              2345
                              345
                              45
                              5
                              The details of the class is given below:
                              Class name                  :   Pattern
                              Data Members
                              int n                       :   To store number of lines
                              Member Methods
                              void read(int nn)           :   Initialises nn to n
                              void print(int i, int j)      :     Using  the  concept  of recursion,  design  the  method
                                                             print(int, int) which will generate the above pattern
                              static void main()          :   Creates object and calls the other methods

                1       class Pattern
                2       {
                3           int n;

                4           void read(int nn) // parameterised input
                5           {

                6               n = nn;
                7           }

                8
                9           void print(int i, int j)

                10          {
                11              if(i>n)    // base case

                12                  System.out.println();
                13              else if(j>n)

                14              {
                15                  System.out.println();

                16                  print(i+1, i+1);
                17                // cursor goes to next line and both row and column change

                18              }
                19              else

                20              {
                21                  System.out.print(j);  // number printed

                22                  print(i, j+1);  // column changes
                23              }



                374374  Touchpad Computer Science-XI
   371   372   373   374   375   376   377   378   379   380   381