2-D Arrays

6
2-D Arrays Declaration & Initialization

description

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. - PowerPoint PPT Presentation

Transcript of 2-D Arrays

Page 1: 2-D Arrays

2-D Arrays

Declaration & Initialization

Page 2: 2-D Arrays

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];

Page 3: 2-D Arrays

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}};

Page 4: 2-D Arrays

Filling a 2d array

for(i=0; i<rows; i++) {for(j=0; j<cols; j++) {

x[i][j] = rand()%10;}

}

Page 5: 2-D Arrays

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 54 3 2 4 3 4 5 1 2 3 2 2 4 3 11 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]?

Page 6: 2-D Arrays

Survey#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++;

}

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);}