Your matrix is wrong.
To begin with, you have a big bug in your program when creating the matrix:
int matriz[fila][columna];
In C ++ the sizes of the 1 formations must be known at compile time, but in your case fila
and columna
are known at run time. If it works for you it will be because your compiler offers that possibility as an extension but other compilers would reject that code or your compiler could decide to stop supporting that extension. Read these questions to learn more about the topic.
You also have a conceptual error: if you want square matrices, why do you ask for both width and height? Order only the side and use it to make the matrix square by design:
Your matrix should be like this.
int *matriz = new int[lado * lado];
This is the correct way to create a matrix whose size is known at runtime; unfortunately C ++ does not offer ways to create two-dimensional formations using the operator new
, so what we create is a one-dimensional formation but we will treat it as if it were two-dimensional with simple pointer arithmetic.
From 1D to 2D.
Having a two-dimensional square matrix stored in a one-dimensional formation, to obtain the element of the row y
and column x
we should calculate its position in the following way:
Element index = (and * side) + x
An auxiliary function can be useful:
int &elemento(int *&matriz_cuadrada, int lado, int x, int y) {
return matriz_cuadrada[(y * lado) + x];
}
Square.
An auxiliary matrix will be necessary to perform the operation since it is necessary to consult the original cells. On the other hand, since the matrix multiplication implies adding the row and column products, it would be useful to have some auxiliary functions that do this operation:
int opera_fila(int *&matriz_cuadrada, int fila, int lado) {
int resultado{};
for (int x = 0; x < lado; ++x)
{
auto valor = elemento(matriz_cuadrada, lado, x, fila);
resultado += (valor * valor);
}
return resultado;
}
int opera_columna(int *&matriz_cuadrada, int columna, int lado) {
int resultado{};
for (int y = 0; y < lado; ++y)
{
auto valor = elemento(matriz_cuadrada, lado, columna, y);
resultado += (valor * valor);
}
return resultado;
}
And finally the function could look like:
void cuadrado(int *&matriz_cuadrada, int lado) {
int *matriz = new int[lado * lado];
for (int y = 0; y < lado; ++y)
{
for (int x = 0; x < lado; ++x)
{
elemento(matriz, lado, x, y) = opera_fila(matriz_cuadrada, y, lado) + opera_columna(matriz_cuadrada, x, lado);
}
}
std::copy(matriz, matriz + (lado * lado), matriz_cuadrada);
delete[] matriz;
}
You can see the code working in Wandbox 三 へ (へ ਊ) へ ハ ッ ハ ッ , you have to correct it as an exercise.