简体   繁体   中英

How to read 2D arrays in C?

I'm learning about 2D arrays in C and I'm a bit confused. I have the following program which reads a 2D arrays and adds its values in another array.

#include <stdio.h>
int main() {        
    int arr[4][5] = {{1,2,3,4,5},
                     {3,1,1,5,2},
                     {4,1,4,1,5},
                     {2,5,3,3,4}};
    int many[4];
    int i;

    for (i=0;i<4;i++) {
        many[i] = arr[i][i] + arr[i][i];
        printf("%d\n", many[i]);
    }

The output of this program is:

2
2
8
6

But I think it should be 3, 3, 9, 7 because the for loop starts at 1 and the first column and row gets 1 and second column and row get 2 because there is already 1 which means 1+1 = 2 and 2 + 1 = 3, for second number it is same idea. For the third number I got 9 because we get 4 from row 2 column 2. 4 + 4 + 1 = 9 and for last number I got 7 because last row has 3 in row 3 column 3.

The output you get is absolutely right for this loop.

  for (i=0;i<4;i++)
{
    many[i] = arr[i][i] + arr[i][i];
    printf("%d\n", many[i]);
}

You can easily get to know it by tracing .


so let's trace it...

during i=0

arr[0][0] denotes 1st element (as indices start from 0) of 1st array which is 1

many[0] = arr[0][0]+arr[0][0] // 1+1=2

during i=1

arr[1][1] denotes 2nd element of 2nd array which is also 1

many[0] = arr[1][1]+arr[1][1] // 1+1=2

during i=2

arr[2][2] denotes 3rd element of 3rd array which is 4

many[2] = arr[2][2]+arr[2][2] // 4+4=8

during i=3

arr[3][3] denotes 4th element of 4th array which is 3

many[3] = arr[3][3]+arr[3][3] // 3+3=6

Therefore,The output of this program is:

2
2
8
6

Note: arr[m][n] denotes (n+1)th element of (m+1)th array

You need 2 loops to iterate through your 2D array

    #include <stdio.h>

    int main() {
        int arr[4][5] = {{1,2,3,4,5},
                         {3,1,1,5,2},
                         {4,1,4,1,5},
                         {2,5,3,3,4}};
        int many[4];
        int i;
        int j;
        for(i=0;i<4;i++)
        {
            many[i] = 0;
            for(j=0;j<5;j++)
            {
                many[i] += arr[i][j];
            }
            printf("%d\n", many[i]);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM