[Legacy Content] This page contains very old information, which might not be valid anymore, they are only kept here for legacy purposes.
if you have any inquiries, feel free to contact me! Click here

2D Arrays - Examples & Solutions

Created: Tuesday, 10 December 2013 Written by Ehab Eldeeb

The Given Examples - as written in the footer of the sheet - are prepared by the computer department staff in AAST
I don't know whom exactly, But thank you for those ideas :)

Solutions are purely written by Ehab Eldeeb

Enjoy :)

 

Unlike the strings sheet, this sheet is really poor .. only five questions here..

If you have any more ideas and want them solved, send me the question on facebook.

 

Examples

Download the sheet from this link --> Download here

 

Solutions

Question 1:

First loop should be for rows, and the second for columns (as a standard)

And it's preferred to initialize the array inside the main function, not before it.

 

Question 2:

for (int i = 0; i < ROW-SIZE; i++)
        for (int j = 0; j < COLUMN-SIZE; j++)
            z[i][j] = x[i][j] + y[i][j];

 

Question 3:

int main(){
    int x[4][4], y[4][4];

    // Read the two arrays
    for (int i = 0; i < 4; i++){
        for (int j = 0; j < 4; j++){
            printf("Enter Element [%d][%d] for the array X: ", i+1, j+1);
            scanf("%d", &x[i][j]);
            printf("Enter Element [%d][%d] for the array Y: ", i+1, j+1);
            scanf("%d", &y[i][j]);
        }
    }
    return 0;
}

Adding or Subtracting Matrices is as easy as how it's shown in Question 2

 

Transpose means invert rows into columns and columns into rows

You will need to create a transposed array first, then transfer the values to it
Example: to transpose int x[5][4]; .. you will need to make int y[4][5];

for (int i = 0; i < 4; i++){
        for (int j = 0; j < 5; j++){
            y[j][i] = x[i][j];
        }
    }

 

Question 4:

The diagonal means i = j
(0,0), (1,1), (2,2), (3,3), ...etc.

int sum = 0;
for (int i = 0; i < 5; i++){
        for (int j = 0; j < 5; j++){
            if (i == j)
               sum += x[i][j];
        }
    }

 

Question 5:

First Part:

for (int i = 0; i < 5; i++){
        for (int j = 0; j < 5; j++){
            if (x[i][j] != 0)
               num++;
        }
    }

Second Part:

int prod = 1;
for (int i = 0; i < 5; i++){
        for (int j = 0; j < 5; j++){
            if (i == j)
               prod *= x[i][j];
        }
    }

 

That's all about that sheet.

 

More Ideas:

(Question "4" or "5 Second Part") .. If you want to get sum or product of:

elements above the diagonal ... change the if condition to:  j > i

elements under the diagonal ... change the if condition to: i > j

 

Matrix problems should be for educational purpose, not for examination.