-3

How do I add rows and columns to a 3X4 array?

output:

1  2  3  4  10
5  6  7  8  26
9  10 11 12 42

Do I use a for loop? I can't get the logic.

int main()
{  
    int arr[3][4], r, c;

    for (r=0; r < 3; r++)
     {
         for (c=0; c < 4; c++) 
           {
              arr[r][c] = 1+r+c;

              printf("%d ", arr[r][c]);
           }

           printf("\n");
      }

      system("PAUSE");
      return 0;
}
Dave S.
  • 6,349
  • 31
  • 33
nomad
  • 1
  • 3

2 Answers2

0

Currently, your matrix contains the following:

1 2 3 4
2 3 4 5
3 4 5 6

Change arr[r][c] = 1+r+c; to arr[r][c] = 1+c+(COLS*r); where COLS is the number of columns that the matrix has.

1 2 3 4 
5 6 7 8 
9 10 11 12 

You can now iterate through each row and compute the sum:

int i, j;
for (i = 0; i < ROWS; ++i) {
    int sum = 0;
    for (j = 0; j < COLS; ++j) {
        sum += arr[i][j];
    }
    printf("%d\n", sum);
}
Garee
  • 1,274
  • 1
  • 11
  • 15
  • Did you change `1+r+c` to `1+c+(4*r)` ? – Garee Jun 10 '13 at 13:31
  • Using the code that you posted and making no changes other than `1+c+(4*r)` it produces 1..12 for me. There must be a problem elsewhere in your code? – Garee Jun 10 '13 at 13:42
0
    int arr[3][4], r, c, i = 1;

    for (r=0; r < 3; r++){
        int sum = 0;
        for (c=0; c < 4; c++){
            arr[r][c] = i++;
            sum += arr[r][c];
            printf("%2d ", arr[r][c]);
        }
        printf("%d\n", sum);
    }
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70