C ++ Problem printing matrices

6

I want to do this problem: link

  

Problem

     

Given a square matrix of size "n", you must do   that your program turns it 90 degrees to the right.

     

Original matrix

1   2
3   4
     

Matrix Rotated 90 ° to the right

3   1
4   2

My code feels good but it does not work. At the time of printing n matrices, it only prints a very long number that has nothing to do with the matrix.

#include <iostream>
using namespace std;
int main()
{
    int n=0;
    cin>>n;
    int m=n*n;
    int arr[n][n];
    for(int i=0; i<n; i++){
        for(int j=0; j<n; j++){
            cin>>arr[i][j];
        }
    }
    for(int x=0; x<m; x++){
        cout<<arr[(n-x)][x];" ";
    }
    return 0;
}
    
asked by isalvinator 06.10.2016 в 05:02
source

2 answers

5

Your program has several problems.

The first one is in the form of declaring the matrix:

int n=0;
cin>>n;
int arr[n][n];

The C ++ standard indicates that creating arrays in the stack based on dynamic sizes (their size is based on a variable) produces an indeterminate result, which means that in some compilers it may work but in others it does not. It is one of those features that should not be used under any circumstances if you do not want to take unpleasant surprises when changing the compiler (or even the compiler version).

If you need the size of the matrix to be dependent on a variable, you should use STL containers or dynamic memory:

Declaration of an nxn matrix

// Creación
std::vector<std::vector<int>> arr(n,std::vector<int>(n));

// Uso
arr[fila][columna] = 7;

// Destrucción
// -- no aplicable --

Dynamic memory v1

This version simplifies access at the cost of complicating creation and deletion

// Creación
int** arr = new int*[n];
for( auto i=0; i<n; i++ )
  arr[i] = new int[n];

// Uso
arr[fila][columna] = 7;

// Destrucción (opción A)
for( auto i=0; i<n; i++ )
  delete[] arr[i];
delete[] arr;

// Destrucción (opción B)
std::for_each(arr,arr+n,std::default_delete<int[]>());
delete[] arr;

Dynamic memory v2

This version simplifies creation and destruction but complicates access.

// Creación
int* arr = new int[n*n];

// Uso
arr[fila*n+columna] = 7;

// Destrucción
delete[] arr;

Another problem is when you print the data:

cout<<arr[(n-x)][x];" ";

That ; that you have before the quotation marks makes the separation space never print ... it becomes a useless instruction that does absolutely nothing.

Also, since you only want to extract a character, the correct thing would be to replace the double quotes with single quotes (double quotes = string = two bytes, single quotes = char = 1 byte).

cout<<arr[(n-x][x] << ' ';

On the other hand, the access you make to the matrix when it comes to printing the results is a bit strange:

for(int x=0; x<m; x++){
    cout<<arr[(n-x)][x]<<' ';
}

If we execute in steps (we assume n = 2, then m = 4, then arr [2] [2]):

x=0 => arr[n-x][x] = arr[2-0][0] = arr[2][0];
  -> Empezamos mal, arr[2] se sale de los límites del array
x=1 => arr[n-x][x] = arr[2-1][1] = arr[1][1];
  -> Al menos está dentro de los límites del array
x=2 => arr[n-x][x] = arr[2-2][2] = arr[0][2];
  -> Seguimos fuera de los límites del array con el índice 2
x=3 => arr[n-x][x] = arr[2-3][3] = arr[-1][3];
  -> Remate final con acceso al índice -1.

Notice that in the exercise they propose, the second matrix is identical to the first applying the following transformations:

  • The index of the rows is equal to the index of the inverted columns
  • The index of the columns is equal to the index of the rows

Then to print the rotated matrix:

for( int j=0;j<n; j++)
{
  for(int i=n-1; i>=0; i--)
    std::cout << arr[i][j] << ' ';
  std::cout << '\n'; // No hay que olvidar el salto de línea al finalizar la fila
}

Greetings.

    
answered by 06.10.2016 в 09:15
1

I show an example starting from the code of the question, but it is possible to improve it using c , which is faster than c ++ :

#include <iostream>

using namespace std;

int main()
{
    int n;
    cin >> n;                                     // Pide el tamaño de la matriz.

    int arr[n][n],
        r[n][n];                                  // Resultado.

    for(int f = 0; f < n; f++)                    // Pide el contenido de la matriz.
        for(int c = 0; c < n; c++)
            cin >> arr[f][c];

    for(int f = 0; f < n; f++)                    // Rota la matriz original arr[][] sobre
        for(int c = 0; c < n; c++)                // la matriz resultado r[][]
            r[f][c] = arr[n - c - 1][f];

    for(int f = 0; f < n; f++)                    // Muestra el resultado.
    {
        cout << endl;
        for(int c = 0; c < n; c++)
            cout << r[f][c] << " ";
    }

    return 0;
}

Now there are two tasks left:

  • Adjust the code according to the omegaUp challenge.
  • Translate it to c to achieve greater efficiency.
answered by 06.10.2016 в 08:54