C++ program to print the boundary elements of a matrix

In this tutorial, we will learn how to find the matrix boundary elements using C++ with some cool and easy examples. In many situations, you might have to come up with this type of requirement.

I know you are here just because you need this awesome trick. Print only the boundary elements of the matrix and the sum of the boundary elements of the matrix.

Steps to print the boundary elements of a matrix in C++

  • first, the computer reads the value of m and n from the user.
  • m is used for row matrix and n is used for the column matrix.
  • then using for loop and if else condition for finding the boundary elements.
  • The sum of the boundary elements of the matrix.
  • finally, the boundary elements and sum of the matrix are printed.

Also learn:

Program to print the boundary elements of a matrix in C++

#include<iostream>
#include<math.h>
using namespace std;

int main()
{
int m, n, sum = 0;
int A[100][100];
cout << "Enter the order of the matrix : "<<endl;
cin >> m >> n;
cout << "Input the matrix elements"<<endl;
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
cin >> A[i][j];
}
cout<<"...................."<<endl;  // for more reliable
cout << "Boundary Matrix"<<endl;
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
if (i == 0 || j == 0 || i == m-1  || j == n-1)
{
cout << A[i][j]<<" " ;
sum = sum + A[i][j];
}
else
cout << " "
     << " ";
}
cout << endl;
}
cout<<"...................."<<endl; // for more reliable
cout << "Sum of boundary is " << sum << endl;
return 0;
}
input: rows(m)=5;
       columns(n)=5;
enter the elements of the matrix :-
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5 
1 2 3 4 5
1 2 3 4 5
output:
...................................................... 
1 2 3 4 5 
1       5
1       5
1       5
1 2 3 4 5
......................................................
sum of the matrix is =48;

Step by step working of the above program code:-

  • First initialized the variables.
  • Then, entered by the user input of the matrix.
  • and also entered by the user input of the matrix elements.
  • Then used for a loop & if else logical condition then gets boundary elements and the sum of the matrix.
  • Finally, Output gets printed.

Leave a Reply

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