Print the corner elements of the matrix using C++

In this tutorial, we will learn how to print the Corner elements of the matrix using C++.

The program prints the top left element, top right element, bottom left element and bottom right element as output.

Input in Matrix format

It is a rows*columns (i.e) the rows and columns can be of any length.

The matrix consists of ‘r’ rows and ‘c’ columns.

 

int rows,cols;
cin>>rows;
cin>>cols;
int matrix[rows][cols];

In the above code, we have initialised rows and cols variables to get the number of rows and number of columns in this matrix.

How to get the matrix as input?

for(int i=0;i<rows;i++){
   for(int j=0;j<cols;j++){
       cin>>matrix[i][j];
   }
}

In the above code segment, the first for loop denotes the row index position where i=0 is the row index.

The second for loop denotes the column index position where j=0 is the column index.



Input format:

Enter the number of rows and columns of the matrix: 3 4
Enter the matrix elements:
1 2 3 4
5 6 7 8
9 10 11 12

CPP code to print the corner elements of the matrix

#include<iostream.h>
using namespace std;
int main(){
int rows,cols;
cout<<"Enter the number of rows and columns of the matrix:"<<"\t";
cin>>rows;
cin>>cols;
int matrix[rows][cols];
cout<<"Enter the matrix elements:"<<"\n";
    for(int i=0;i<rows;i++){
       for(int j=0;j<cols;j++){
          cin>>matrix[i][j];
       }
    }
cout<<"THE CORNER ELEMENTS OF THE MATRIX ARE:"<<"\n";
     for(int i=0;i<rows;i++){
        for(int j=0;j<cols;j++){
            if(i==0&&j==0){
              cout<<"Top Left Element of the matrix:"<<"\t";
              cout<<matrix[0][0]<<"\n";
            }
            if(i==0&&j==cols-1){
              cout<<"Top Right Element of the matrix:"<<"\t";
              cout<<matrix[i][j]<<"\n";
            }
            if(i==rows-1&&j==0){
              cout<<"Bottom Left Element of the matrix:"<<"\t"; 
              cout<<matrix[i][j]<<"\n";
            }
            if(i==rows-1&&j==cols-1){
               cout<<"Bottom Right Element of the matrix:"<<"\t";
               cout<<matrix[i][j]<<"\n";
            }
         }
     }
}

In the above code,

  • First if checks i==0 and j==0 and prints the first element.
  • The if statement checks i==0 and j==cols-1 and prints the top right element.
  • The third if statement checks i==rows-1 and j==0 and prints bottom left element.
  • The next if statement checks i==rows-1 and j==cols-1 and prints bottom right element.

Output:

THE CORNER ELEMENTS OF THE MATRIX ARE:
Top Left Element of the matrix: 1
Top Right Element of The matrix: 4
Bottom Left Element of the matrix: 9
Bottom Right Element of the matrix: 12

Therefore the program prints the corner elements of the matrix.
We hope this tutorial helped you to understand how to print the corner elements of the matrix.

Leave a Reply

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