Download presentation
Presentation is loading. Please wait.
Published byAmy Sullivan Modified over 8 years ago
1
2-D Arrays Declaration & Initialization
2
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];
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}};
4
Filling a 2d array for(i=0; i<rows; i++) { for(j=0; j<cols; j++) { x[i][j] = rand()%10; }
5
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: 1 4 5 3 5 3 4 5 1 1 2 3 2 4 5 4 3 2 4 3 4 5 1 2 3 2 2 4 3 1 1 2 3 2 3 4 3 4 5 3 4 2 1 2 5 … 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]?
6
Survey #include #define NLINES 100 #define NQUEST 15 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++; } Sz=--i; /* Print array */ for(i=0; i<Sz; i++) { for(j=0; j<NQUEST; j++) printf("%d ", Sarr[i][j]); printf("\n"); } fclose(flp); return(0); }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.