how can i do it with one loop?

``````void printMat(const int mat[][N], int n)
{
int i, j;
for(i = 0; i < n; i++)
{
for(j = 0; j < N; j++)
printf("%3d ", mat[i][j]);
puts("");
}
}``````

Write out what the loop would be printing for a 2x3 case

``````mat[0][0],        mat[0][1],      mat[0][2],     mat[1][0],    mat[1][1],          mat[1][2]
0                  1              2              3               4              5``````

So how do you get 0 to be [0][0], 1 to be [0][1], etc, 5 to be [1][2]

All else fails, pop it into a compiler and mess around with different combos.

Happy Holidays

If you know the RowSize and colSize you can do this, but I see no point.
Using 2 for loops makes it more clear.

``````void print(int A[MAX_ROW][MAX_COL])
{
int row = 0;
int col = 0;

for(row = 0, col = 0; row < MAX_ROW; )
{
//increment row and reset col if it reaches the end
if(col != 0 && col % MAX_COL == 0)
{
row++;
col = 0; //reset column
printf("\n");
}
if(row < MAX_ROW)
printf("%i ", A[row][col]);

col++;
}
}``````

I am unsure of the efficiency of my method, but I like to use (if using one loop is really a big deal; usually the choice is out of ease):

``````for(int i = 0; i < ROWS * COLS; i++)
{
printf("%i ", arr[i/ROWS][i%COLS]);
}``````

If you know the RowSize and colSize you can do this, but I see no point.
Using 2 for loops makes it more clear.

I suspect this is the kind of thing that becomes fodder in "My professor is better than yours" arguments as to who can produce these snazzy little tricks at parties. I'm unconvinced that this isn't an assignment.

I am unsure of the efficiency of my method, but I like to use (if using one loop is really a big deal; usually the choice is out of ease):

``````for(int i = 0; i < ROWS * COLS; i++)
{
printf("%i ", arr[i/ROWS][i%COLS]);
}``````

I got something similar but did you use a square matrix to derive your result?
I was just trying to let the OP derive it him or herself but this will give him/her a boost in the right direction.

I got something similar but did you use a square matrix to derive your result?

I wouldn't say I "derived" it from anything, possibly because I don't quite understand the question. The idea came from a simple file-explorer GUI I was working on.

I wouldn't say I "derived" it from anything, possibly because I don't quite understand the question.

That's totally my bad, I was not trying to be accusatory at all. I asked because I did it out with pencil and paper with a 2x2 case and at first got what you did, but I believe (and I still could be wrong lol) that it's only a function of columns.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.