### Arrays 2d

```2-D Arrays
Declaration & Initialization
Declaration
• You can think of 2D arrays as a matrix rows
and columns:
– a 4x3 matrix
2 5 4
1 3 7
6 2 1
9 8 0
– 4 rows and 3 columns
– int x[4][3];
Declaration and Initialization
int x[4][3] = {{1, 2, 4}, {2, 3, 5}, {1, 4, 2}, {4, 3, 1}};
–
–
–
–
x[1][2]  ?
x[3][1]  ?
?
?
int x[][3] = {{1, 2, 4}, {2, 3, 5}, {1, 4, 2}, {4, 3, 1}};
int x[4][3] = {1, 2, 4, 2, 3, 5, 1, 4, 2, 4, 3, 1};
int x[][3] = {1, 2, 4, 2, 3, 5, 1, 4, 2, 4, 3, 1};
int x[4][3] = {1, 2, 4, 2, 3, 5, 1, 4};
int x[4][3] = {{1, 2, 4}, {2, 3, 5}, {1, 4, 0}, {0, 0, 0}};
Filling a 2d array
for(i=0; i<rows; i++) {
for(j=0; j<cols; j++) {
x[i][j] = rand()%10;
}
}
Survey
• A survey has 15 questions and each question has 5 answers. The
survey results are in a file called Survey.txt in the following format:
145353451123245
432434512322431
123234345342125
…
•
Read each survey result into an array
–
–
–
•
•
•
How many people surveyed? Number of lines (Nlines).
How many questions in each survey? Number of columns = 15
(Nquest)
How many different values for each question? 5 (Nvalue)
Need to use two dimensional array
int Srvy[Nlines][Nquest]
What is the value of Srvy[2][10]?
Survey
Sz=--i;
#include <stdio.h>
#define NLINES 100
#define NQUEST 15
/* Print array */
for(i=0; i<Sz; i++) {
for(j=0; j<NQUEST; j++)
printf("%d ", Sarr[i][j]);
printf("\n");
}
int main(void) {
FILE*flp;
intSarr[NLINES][NQUEST] = {0};
inti, j;
intStatus=1, Sz;
flp = fopen("Survey.txt", "r");
/* Fill array */
i=0;
while(Status != EOF) {
for(j=0;j<NQUEST;j++) {
Status = fscanf(flp, "%d", &Sarr[i][j]);
if(Status == EOF) break;
}
i++;
}
fclose(flp);
return(0);
}
```