Fill a 5 x 5 matrix using only one for C / C ++? [closed]

-2

Does anyone know how to fill a 5 x 5 matrix only using a for?

    
asked by Alberto Castillo 05.09.2018 в 05:41
source

1 answer

4

I understand that the matrix is fixed in size:

int matriz[5][5];

In this case there is good news for you, the compiler prepares this matrix so that its cells occupy consecutive positions in memory:

[0][0] [0][1] [0][2] [0][3] [0][4] [1][0] [1][1] ...

So if you want to go through it with a single for you can use a simple pointer:

int* ptr = (int*)matriz;
for( int i=0; i<25; ++i, ++ptr )
  std::cin >> *ptr;

In the general case, that is, that the matrix does not occupy consecutive memory positions (for example a dynamic double pointer), or if it is because you want to do it explicitly, you can calculate the row and the column to which belongs to each index:

for( int i=0; i<25; i++ )
{
  int fila = i / 5;
  int columna = i % 5;

  std::cin >> matriz[fila][columna];
}
    
answered by 05.09.2018 в 07:44