Page 386 - ComputerScience_Class_11
P. 386

Program 14     Create the following class:
                               class name       :    spiral
                               Data members     :    int sparr[][] – stores the matrix in spiral format
                               int s            :   Size of the matrix
                               Method:
                               spiral(int n)    :    constructor to initialise s=n and create the matrix in spiral format.
                               void display()   :    Display the matrix
                               Example of spiral matrix:

                                             Clockwise


                                  1       2      3      4      5

                                  16     17     18     19      6


                                  15     24     25     20      7

                                  14     23     22     21      8

                                  13     12     11     10      9


                1       public class Spiral

                2       {

                3           int[][] sparr;
                4           int s;

                5
                            Spiral(int n)
                6           {

                7               s = n;
                8               sparr = new int[s][s];

                9               int left = 0, right = s - 1, top = 0, bottom = s - 1;

                10              int num = 1;
                11              while (num <= s * s)

                12              {
                13                  for (int i = left; i <= right; i++)

                14                  {
                15                      sparr[top][i] = num++;

                16                  }

                17                  top++;
                18                  for (int i = top; i <= bottom; i++)






                  384  Touchpad Computer Science (Ver. 3.0)-XI
   381   382   383   384   385   386   387   388   389   390   391