I am trying to print the following pattern:
n = 2 n = 5
2 2 2 5 5 5 5 5 5 5 5 5
2 1 2 5 4 4 4 4 4 4 4 5
2 2 2 5 4 3 3 3 3 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 2 1 2 3 4 5
5 4 3 2 2 2 3 4 5
5 4 3 3 3 3 3 4 5
5 4 4 4 4 4 4 4 5
5 5 5 5 5 5 5 5 5
This is what I have tried which works for n = 1,2,3
Code Snippet:
#include <iostream>
using std::cout;
using std::cin;
int main()
{
int n,m;
cin>>n;
m = 2*n - 1;
int **arr = new int*[m];
for(int i = 0; i < m; i++)
arr[i] = new int[m];
for(int i = 0; i < m; i++)
{
for(int j = 0; j < m; j++)
{
if(i == 0 or j == 0 or i == m - 1 or j == m - 1)
arr[i][j] = n;
else if (i == 1 or j == 1 or i == m - 2 or j == m - 2)
arr[i][j] = n - 1;
else
arr[i][j] = 1;
}
}
for(int i = 0; i < m; i++)
{
for(int j = 0; j < m; j++)
{
cout<<arr[i][j]<<" ";
}
cout<<"\n";
}
return 0;
}
For other inputs I need to generalize the if-else tree using a loop. I tried using the following snippet,
for(int k = 0; k < m; k++)
if(i == k or j == k or i == m - k - 1 or j == m - k - 1)
arr[i][j] = n - k;
Output for n = 2:
0 0 0
0 1 0
0 0 0
Update: Based on the first code snippet, what I understand is the for loop in the second code snippet is missing the else part.