CS157: Intro to C, Part II

Spring 2018

Multi D Arrays

See this page as a slide show

Multi-Dimensional Arrays

CS157 MultiDArrays

Two-Dimensional Arrays

int val[3][4]; // 3 rows, 4 columns

Two-Dimensional Arrays

 Column 0Column 1Column 2Column 3
Row 0816952
Row 1315286
Row 21425210

Two-Dimensional Arrays

Initialization:

#define NUMROWS 3
#define NUMCOLS 4
int val[NUMROWS][NUMCOLS] = { { 8, 16,  9, 52},
                              { 3, 15, 27,  6},
                              {14, 25,  2, 10} };

First row is an array containing {8, 16, 9, 52}.

The inner braces can be omitted, if you have no soul:

int val[NUMROWS][NUMCOLS] =
    {8,16,9,52,3,15,27,6,14,25,2,10};

Initialization

 Column 0Column 1Column 2Column 3
Row 0firstsecondthirdfourth
Row 1fifthsixthseventheighth
Row 2ninthtentheleventhtwelfth

Two-Dimensional Arrays

#define NUMROWS 3
#define NUMCOLS 4
int val[NUMROWS][NUMCOLS] = {{8,16,9,52},
                             {3,15,27,6},
                             {14,25,2,10}};

printf("The hard way:\n");
printf(" %2d %2d %2d %2d\n",
       val[0][0], val[0][1], val[0][2], val[0][3]);
printf(" %2d %2d %2d %2d\n",
       val[1][0], val[1][1], val[1][2], val[1][3]);
printf(" %2d %2d %2d %2d\n",
       val[2][0], val[2][1], val[2][2], val[2][3]);

printf("The easy way:\n");
for (int i=0; i<NUMROWS; i++) {
    for (int j=0; j<NUMCOLS; j++)
        printf(" %2d", val[i][j]);
    printf("\n");
}
The hard way:
  8 16  9 52
  3 15 27  6
 14 25  2 10
The easy way:
  8 16  9 52
  3 15 27  6
 14 25  2 10

Two-Dimensional Arrays

#define NUMROWS 3
#define NUMCOLS 4
int val[NUMROWS][NUMCOLS] = {{8,16,9,52},
                             {3,15,27,6},
                             {14,25,2,10}};

/* Multiply each element by 10 and display it */
for (int i=0; i<NUMROWS; i++) {
    for (int j=0; j<NUMCOLS; j++) {
        val[i][j] *= 10;
        printf(" %3d", val[i][j]);
    }
    printf("\n");
}
  80 160  90 520
  30 150 270  60
 140 250  20 100

Two-Dimensional Arrays

#define NUMROWS 3
#define NUMCOLS 4

void display(int array[NUMROWS][NUMCOLS]);

int main() {
    int val[NUMROWS][NUMCOLS] = {{8,16,9,52},
                                 {3,15,27,6},
                                 {14,25,2,10}};
    display(val);
    return 0;
}

void display(int nums[NUMROWS][NUMCOLS]) {
    /* Multiply each element by 10 and display it */
    for (int i=0; i<NUMROWS; i++) {
        for (int j=0; j<NUMCOLS; j++) {
            nums[i][j] *= 10;
            printf(" %3d", nums[i][j]);
        }
        printf("\n");
    }
}
  80 160  90 520
  30 150 270  60
 140 250  20 100

Common Programming Errors

Summary of 1D arrays

Summary of 2D arrays

Even Worse

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2018-04-22T14:04

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building