2d arrays

Need some help pals, let us say that we have a square matrix and the task is to display the first 2 inner squares from it.

Initial matrix :

00 01 02 03 04
10 11 12 13 14
20 21 22 23 24
30 31 32 33 34
40 41 42 43 44
50 51 52 53 54

Should display :

00 01 02 03 04
10 11 12 13 14
20 21 --- 23 24
30 31 --- 33 34
40 41 42 43 44
50 51 52 53 54


I am trying something to built but as far as I see I'm too far from what is meant to be displayed,


1
2
3
4
5
6
7
8
9
10
  for(int i=0; i<n; i++)
          {
             for(int j=0; j<m; j++)
             {
               if( M[0][j] && M[1][j] && M[ (n-1) ][j] && M[ i ][(n-1)] && M[ i ][0]) cout<<setw(3)<<M[i][j];
               else cout << " "<< endl;
             }
            cout<<endl;
        }
        cout<<endl;


Please enlighten me, gimme some hints
Last edited on
did you mean outer squares? That is, on a 100x100, display top two rows, bottom two rows, and the first 2 and last 2 columns?

or something else?

If its what I said, display the top 2 rows in a loop, then the sidebar columns and filled in middle in a loop, and then the last 2 rows. Sure, you can condition it all up to do it in a single loop, but that is more complicated and slower than the 3 loops (conditions take cpu time).

alternately, you can print the whole thing, and replace the innner square with dashes, if you don't mind the conditional.
in that case, if the rows are > 1 (0 and 1 are first 2 rows) and less than maxrow-1 (eg your example 6 rows, -1 is 5, less than 5 is 4,3,2,1,0 but the first part took out 0 and 1 so you mess with rows 4,3,2 only) and similar for columns -- if on valid rows to tamper with, you check that columns are >1 and < maxcol-1 exact same idea.

you are looking at the DATA. you need to look at the INDEX.
M[0][j] && M[1][j]
that says it is true if the data in [0][j] and the data in [1][j] are both nonzero. Nothing like what you want.
Last edited on
That's a very wonky "square" matrix, I think.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
   const int N = 10;
   const int ROWS = 6, COLS = 5, MARGIN = 2;

   int M[N][N];
   for ( int i = 0; i < N; i++ )
   {
      for ( int j = 0; j < N; j++ ) M[i][j] = 10 * i + j;
   }

   cout.fill( '0' );
   for ( int i = 0; i < ROWS; i++ )
   {
      for ( int j = 0; j < COLS; j++ )
      {
         if ( i >= MARGIN && i < ROWS - MARGIN && 
              j >= MARGIN && j < COLS - MARGIN ) cout << setw( 2 ) << "--"   ;
         else                                    cout << setw( 2 ) << M[i][j];
         cout << ' ';
      }
      cout << '\n';
   }
}


00 01 02 03 04 
10 11 12 13 14 
20 21 -- 23 24 
30 31 -- 33 34 
40 41 42 43 44 
50 51 52 53 54
Last edited on
@jonnin @lastchance thank you so much for all your help, appreciate it!
Topic archived. No new replies allowed.