3 Attachment(s)
Help - Walk in a bidimensional array
Hello everyone!
What I have to do is to print a bidimensional array of N*N like this:
Attachment 13371
What I tried to do was:
- a function called Right that goes to the right
- a function called Left that goes to the left
- a function called Up that goes up
- a function called Down that goes down
Like this:
Attachment 13372
As you can see, in the first bidimensional array, N=6. I have to go 3 times right, 3 times left, 2 times up and 2 times down. So, I have to go N/2 times to the left and to the right, and (N/2 - 1) times to up and down.
In the second bidimensional array, N=7. I have to go 3 times to left, right, up and down. So, I have to go N/2 times to left, right, up and down, and, in the end, I have to add the number that is in [N/2][N/2]
Here's the code. It works fine for this columns and rows:
Attachment 13370
but I don't know how to do a for that says the program how much times to do those 4 steps.
I know how many times they have to be done:
- If N/2==0, the program has to do (N/2) times to left and right, and (N/2 -1) times up and down
- If N/2==1, the program has to do (N/2) times to left, right, up and down, and I have to add the number in the element [N/2][N/2]
Code:
#include <stdio.h>
#include <stdlib.h>
void CompleteBidimArray(int rows, int cols, int mat[rows][cols])
{
int i, j;
for(i=0; i<rows; i++)
{
for(j=0; j<cols; j++)
{
printf("\n[%d][%d]: ", i, j);
scanf("%d", &mat[i][j]);
}
}
}
void PrintOriginalBidimArray(int rows, int cols, int mat[rows][cols])
{
int i, j;
for (i=0; i<rows; i++)
{
for(j=0; j<cols; j++)
{
printf("%4d", mat[i][j]);
}
printf("\n");
}
}
void Right (int rows, int cols, int InitialRow, int mat[rows][cols])
{
int InitialCol=InitialRow;
int j;
printf("\n\nRIGHT\n");
for(j=InitialCol; j<(cols-InitialCol); j++)
{
printf("%4d", mat[InitialRow][j]);
}
}
void Down(int rows, int cols, int InitialCol, int mat[rows][cols])
{
int InitialRow=cols-InitialCol;
int i;
printf("\n\nDOWN\n");
for(i=InitialRow; i<(rows-InitialRow); i++)
{
printf("%4d", mat[i][InitialCol]);
}
}
void Left (int rows, int cols, int FinalCol, int mat[rows][cols])
{
int FinalRow=FinalCol;
int j;
printf("\n\nLEFT\n");
for(j=FinalCol; j>(cols-FinalCol-2); j--)
{
printf("%4d", mat[FinalRow][j]);
}
}
void Up (int rows, int cols, int FinalRow, int mat[rows][cols])
{
int FinalCol=cols-FinalRow-1;
int i;
printf("\n\nUP\n");
for(i=FinalRow-1; i>(rows-FinalRow-1); i--)
{
printf("%4d", mat[i][FinalCol]);
}
}
int main()
{
int rows, cols;
printf("\nRows: ");
scanf("%d", &rows);
printf("\nColumns: ");
scanf("%d", &cols);
int mat[rows][cols];
CompleteBidimArray(rows, cols, mat);
PrintOriginalBidimArray(rows, cols, mat);
Right(rows, cols, 0, mat);
Down(rows, cols, cols-1, mat);
Left(rows, cols, cols-1, mat);
Up(rows, cols, cols-1, mat);
if(rows%2==1)
{
printf("\n\n %d", mat[rows/2][cols/2]);
}
return 0;
}
Thankssssssss! :D
Juan