#include <iostream>
using namespace std;
const int MAX = 100;
void pritnBoundry(int arr[][MAX], int m, int n){
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(i==0 || j==0 || i == n-1 || j == n-1){
cout<<arr[i][j]<<" ";
}
else{
cout<<" "<<" ";
}
}
cout<<endl;
}
}
int main(){
int arr[4][MAX] = {{1,2,5,8},
{2,5,2,6},
{8,6,9,4},
{7,9,5,6}};
pritnBoundry(arr,4,4);
return 0;
}
Output:
1 2 5 8
2 6
8 4
7 9 5 6
Explanation:
Step 1: Include Libraries and Define Constants
#include <iostream>
using namespace std;
const int MAX = 100;
#include <iostream>: This includes the Input/Output Stream library, which allows us to use functions likecinandcoutfor input and output.using namespace std;: This statement allows us to avoid prefixing standard C++ functions withstd::. For example, we can usecoutinstead ofstd::cout.const int MAX = 100;: This defines a constantMAX, which is the maximum size of the 2D array’s second dimension (columns). We assume the array won’t have more than 100 columns.
Step 2: Function to Print Boundary Elements
void printBoundary(int arr[][MAX], int m, int n) {
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 << arr[i][j] << " ";
}
else {
cout << " "; // Add spaces to align output
}
}
cout << endl; // Move to the next line after printing each row
}
}
printBoundaryFunction: This function takes a 2D arrayarr, the number of rowsm, and the number of columnsnas arguments. It prints the boundary elements of the array and leaves blank spaces for non-boundary elements.- Outer loop (
for i): Iterates over the rows of the array. - Inner loop (
for j): Iterates over the columns of the array. - Boundary Condition (
if):i == 0: True for the first row.j == 0: True for the first column.i == m-1: True for the last row.j == n-1: True for the last column.
- If any of these conditions is true, the element is part of the boundary and gets printed.
cout << " ";: Prints two spaces to maintain alignment for non-boundary elements.cout << endl;: Moves to the next line after printing each row.
Step 3: Main Function
int main() {
int arr[4][MAX] = {{1, 2, 5, 8},
{2, 5, 2, 6},
{8, 6, 9, 4},
{7, 9, 5, 6}};
printBoundary(arr, 4, 4);
return 0;
}
arr[4][MAX]: This declares a 2D array with 4 rows and a maximum ofMAXcolumns. However, only the first 4 columns are initialized with values.- Array Elements: The array is initialized with the following values:
{ {1, 2, 5, 8},
{2, 5, 2, 6},
{8, 6, 9, 4},
{7, 9, 5, 6} }
- Calling
printBoundary(arr, 4, 4): This function call passes the array, the number of rows (4), and the number of columns (4) to theprintBoundaryfunction to print the boundary elements.
