Let's say that instead of writing
for (int i = 0; i < I; i) {
for (int j = 0; j < J; j) {
/* do whatever */
}
}
I write
for (int k = 0; k < I * J; k) {
/* who do I calculate indices i and j? */
}
how do I calculate the two previous indices i and j?
CodePudding user response:
Here you are
i = k / J;
j = k % J;
Here is a demonstration program
#include <stdio.h>
int main( void )
{
enum { I = 2, J = 3 };
int a[I][J] =
{
{ 1, 2, 3 },
{ 4, 5, 6 }
};
for ( int i = 0; i < I; i )
{
for ( int j = 0; j < J; j )
{
printf( "%d ", a[i][j] );
}
putchar( '\n' );
}
putchar( '\n' );
for ( int k = 0, N = I * J; k < N; k )
{
printf( "%d ", a[k / J][k % J] );
if ( ( k 1 ) % J == 0 ) putchar( '\n' );
}
}
The program output is
1 2 3
4 5 6
1 2 3
4 5 6
Or if to use a 3D array then the program can look the following way
#include <stdio.h>
int main()
{
enum { I = 2, J = 3, K = 4 };
int a[][J][K] =
{
{
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }
},
{
{ 13, 14, 15, 16 },
{ 17, 18, 19 , 20 },
{ 21, 22, 23, 24 }
}
};
for ( int i = 0; i < I; i )
{
for ( int j = 0; j < J; j )
{
for ( int k = 0; k < K; k )
{
printf( "- ", a[i][j][k] );
}
putchar( '\n' );
}
putchar( '\n' );
}
putchar( '\n' );
for ( int k = 0, N = I * J * K; k < N; k )
{
printf( "- ", a[k / ( J * K )][k % ( J * K ) / K][k % (J * K ) % K] );
if ( ( k 1 ) % K == 0 ) putchar( '\n' );
if ( ( k 1 ) % ( J * K ) == 0 ) putchar( '\n' );
}
}
Its output is
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20
21 22 23 24
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20
21 22 23 24
CodePudding user response:
#include <stdio.h>
int main(void) {
const int I = 7;
const int J = 4;
for (int k = 0; k < I * J; k) {
int i = k/J;
int j = k%J;
printf("Calculated i,j: %d,%d\n", i, j);
}
return 0;
}
As the output demonstrates, the calculated i
value goes from 0
to 6
, and the calculated j
value goes from 0
to 3
.
Success #stdin #stdout 0.01s 5444KB
Calculated i,j: 0,0
Calculated i,j: 0,1
Calculated i,j: 0,2
Calculated i,j: 0,3
Calculated i,j: 1,0
Calculated i,j: 1,1
Calculated i,j: 1,2
Calculated i,j: 1,3
Calculated i,j: 2,0
Calculated i,j: 2,1
Calculated i,j: 2,2
Calculated i,j: 2,3
Calculated i,j: 3,0
Calculated i,j: 3,1
Calculated i,j: 3,2
Calculated i,j: 3,3
Calculated i,j: 4,0
Calculated i,j: 4,1
Calculated i,j: 4,2
Calculated i,j: 4,3
Calculated i,j: 5,0
Calculated i,j: 5,1
Calculated i,j: 5,2
Calculated i,j: 5,3
Calculated i,j: 6,0
Calculated i,j: 6,1
Calculated i,j: 6,2
Calculated i,j: 6,3