I am learning C but I am still very new. I face the following problem: given a square matrix I must copy it in another matrix and order it as follows: For example, if I work with this input matrix:
{0,0,0,0,0,0,0,0,0}
{0,0,0,0,0,0,0,0,0}
{0,0,0,0,0,0,0,0,0}
{0,0,0,0,0,0,0,0,0}
{0,1,2,1,1,0,0,0,0}
{1,1,2,0,1,0,0,0,0}
{2,2,1,0,2,1,0,0,0}
{1,1,0,0,0,0,0,0,0}
{0,0,0,0,0,0,0,0,0}
I should get the following output:
{1,2,1,1,1,0,0,0,0}
{1,1,2,1,0,0,0,0,0}
{2,2,1,2,1,0,0,0,0}
{1,1,0,0,0,0,0,0,0}
{0,0,0,0,0,0,0,0,0}
{0,0,0,0,0,0,0,0,0}
{0,0,0,0,0,0,0,0,0}
{0,0,0,0,0,0,0,0,0}
{0,0,0,0,0,0,0,0,0}
I have tried changing the indexes of the matrix, "rising" the values 4 positions upwards but it does not work. The solution must serve for any square matrix. I leave the code that I have worked that works for a 3x3 matrix but with this 9x9 it does not work. I hope you can help me to see what I'm wrong about.
#include <stdio.h>
int main(){
int matriz[9][9]={{0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0},
{0,1,2,1,1,0,0,0,0},
{1,1,2,0,1,0,0,0,0},
{2,2,1,0,2,1,0,0,0},
{1,1,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0},
};
int matriz2[9][9]={{0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0},
};
int m=0;
int n=0;
int i=0;
int j=0;
while(i<9){
while(j<9){
if (matriz[i][j]!=0)
{
while(matriz[i][j]!=0 && j < 9)
{
matriz2[m][n]=matriz[i][j];
n++;
j++;
}
if(j == 9)
m++;
n=0;
}
else
j++;
}
i++;
j=0;
}
for (int i = 0; i < 9; ++i)
{
for (int j = 0; j < 9; ++j)
{
printf("[%d]",matriz2[i][j] );
}
printf("\n");
}
}
this code returns me:
{1,1,1,1,0,0,0,0,0}
{0,0,0,0,0,0,0,0,0}
{0,0,0,0,0,0,0,0,0}
{0,0,0,0,0,0,0,0,0}
{0,0,0,0,0,0,0,0,0}
{0,0,0,0,0,0,0,0,0}
{0,0,0,0,0,0,0,0,0}
{0,0,0,0,0,0,0,0,0}
{0,0,0,0,0,0,0,0,0}