1 / 6

2-D Arrays

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.

Télécharger la présentation

2-D Arrays

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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 • intSrvy[Nlines][Nquest] • What is the value of Srvy[2][10]?

  6. Survey 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); } • #include <stdio.h> • #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++; • }

More Related