How to Print Boundary elements of matrix

0

 Printing the boundary elements of the matrix is one of the basic questions of the matrix. In this post we will see how can we print the boundary elements. 


Input : { {1,3,9,0,2},{4,7,1,4,6},{0,9,6,3,4}}

Output : 1,3,9,0,2,6,4,,3,6,9,0,4

So as we see in the image above we have to write a program through which we can print the boundary elements of the matrix .

We have two codes for this problem one in java and one in c++.

Java Code :


public class Matrix
{
    
    
    public static void printBoundary(int [][] mat,int rows , int cols)
    {
        if(rows==1)
        {
            for(int i=0;i<cols;i++)
                System.out.println(mat[0][i]+" ");
        }
        else{
            if(cols==1){
                for(int i=0;i<rows;i++)
                    System.out.println(mat[i][0]+" ");
            }
            else{
                for(int i=0;i<cols;i++)
                    System.out.print(mat[0][i]+" ");
                for(int i=1;i<rows;i++)
                    System.out.print(mat[i][cols-1]+" ");
                for(int i=cols-2;i>=0;i--)
                    System.out.print(mat[rows-1][i]+" ");
                for(int i=rows-2;i>0;i--)
                    System.out.print(mat[i][0]+" ");
            }

        }
    }
    public static void main(String [] args)
    {
        int [][] mat = { {1,2,3},{3,4,5},{7,2,0},{9,5,3}};
        System.out.println("------------------");
        printBoundary(mat43);
    }
}




C++ Code :

#include<iostream>
public class Matrix
{
    
    public static void printBoundary(int [][] mat,int rows , int cols)
    {
        if(rows==1)
        {
            for(int i=0;i<cols;i++)
                cout<<(mat[0][i]+" ");
        }
        else{
            if(cols==1){
                for(int i=0;i<rows;i++)
                    cout<<(mat[i][0]+" ");
            }
            else{
                for(int i=0;i<cols;i++)
                    cout<<(mat[0][i]+" ");
                for(int i=1;i<rows;i++)
                    cout<<(mat[i][cols-1]+" ");
                for(int i=cols-2;i>=0;i--)
                    cout<<(mat[rows-1][i]+" ");
                for(int i=rows-2;i>0;i--)
                    cout<<(mat[i][0]+" ");
            }

        }
    }
}
int main()
{
    int [][] mat = { {1,2,3},{3,4,5},{7,2,0},{9,5,3}};
    cout<<"------------------";
    printBoundary(mat43);
    return 0;
}





Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !