-3

i function to print an array normally which works. it is an array of 9 ints. i am trying to display it as a 3*3 matrix. For example:

normal print:

1 2 3 4 5 6 0 0 0 

expected output:

1 2 3 
4 5 6 
0 0 0 

Here is the code that first came to mind because for the life of me i could not find a way to use loops to achieve this

  void printArray (int arr[], int n)  
{  
    cout << arr[0] << " " <<arr[1] << " " <<arr[2] << endl;
    cout << arr[3] << " " <<arr[4] << " " <<arr[5] << endl;
    cout << arr[6] << " " <<arr[7] << " " <<arr[8] << endl;
}

i am only using a 1D array.

ChrisMM
  • 8,448
  • 13
  • 29
  • 48
elie1
  • 25
  • 7

2 Answers2

3

You can use the modulus operator to decide whether to print a space or a newline after each item, something like:

void printArray (int *arr, int nRows, int nCols) {
    for (int i = 0; i < nRows * nCols; ++i) {
        cout << arr[i] << ((i % nCols) == nCols - 1) ? '\n' : ' ';
    }
}

Where nCols is three, for example, a space will be printed after all items except the ones at indexes {2, 5, 8, ...}. Those ones will be followed by a newline.


As an aside, you probably don't want to be using endl after every single element. It both outputs a newline and flushes buffers, something that's going to affect performance if you do it a lot. Better to just output the newlines and, if you want to force a flush, do it after the loop with cout.flush().

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
0

You can also convert the 1-D arr to 2-D array and access them by p[row][col]

    int (*p)[3] = (int (*)[3])arr;

    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++ ) {
            cout << p[i][j] << " ";
        }
        cout << endl;
    }

output:

1 2 3 
4 5 6 
0 0 0 
gamesun
  • 227
  • 1
  • 10