icse-promo

Question

Design the class Shift to shuffle the matrix ( i.e. the first row becomes the last , the second row becomes the first and so on). The details of the members of the class is given below:

Classname:Shift

Data member/instance variable:
mat[ ][ ]:stores the array element
m:integer to store the number of rows
n:integer to store the number of columns
Member functions/methods:
Shift(int mm,int nn):parameterized constructor to initialize the data members m=mm and n=nn

void input():enter the element of the array
void cyclic(Shift P):enables the matrix of the object(P) to shift each row upwards in a cyclic manner and store the resultant matrix in the current object
void display():displays the matrix elements

Specify the class Shift giving details of the constructor(),void input(),void cyclic(Shift) and void display(). Define the main() function to create an object and call the methods accordingly to enable the task of shifting the array elements.

Share code with your friends

Share on whatsapp
Share on facebook
Share on twitter
Share on telegram

Code

				
					import java.util.Scanner;
public class Shift
{
    Scanner sc=new Scanner(System.in);
    int mat[][];
    int m,n;
    Shift(int mm,int nn)
    {
        m=mm;
        n=nn;
        mat=new int[m][n];
    }
    
    void input()
    {
        System.out.println("Enter elements of array");
        for(int i=0;i< m;i++)
        {
            for(int j=0;j< n;j++)
            {
                mat[i][j]=sc.nextInt();
            }
        }
    }
   
    void display()
    {
        for(int i=0;i< m;i++)
        {
            for(int j=0;j< n;j++)
            {
                System.out.print(mat[i][j]+" ");
            }
            System.out.println();
        }
    }

    void cyclic(Shift P)
    {
        for(int i=0;i< m;i++)
        {
            for(int j=0;j< n;j++)
            {
                if(i==0)
                {
                    mat[m-1][j]=P.mat[0][j];
                }
                else
                {
                    mat[i-1][j]=P.mat[i][j];
                }
            }
        }
    }
    
    public static void main()
    {
        Scanner sc1=new Scanner(System.in);
        System.out.println("ENTER THE NUMBER OF ROWS");
        int r=sc1.nextInt();
        System.out.println("ENTER THE NUMBER OF COLUMNS");
        int c=sc1.nextInt();
        Shift ob1=new Shift(r,c);
        Shift ob2=new Shift(r,c);
        ob1.input();
        ob2.cyclic(ob1);
        ob1.display();
        ob2.display();
    }
}



				
			

Coding Store

Leave a Reply

Your email address will not be published. Required fields are marked *