Professional Documents
Culture Documents
14
Introduction to Programming
Two-Dimensional Arrays
In general, an array with m rows and n columns
is called an m x n array (m by n array).
int array[3][4];
col 0 col 1 col 2 col 3
Introduction to Programming
Two-Dimensional Arrays
• The first and second indeces signify the
row and the column of the element in
the array respectively.
• Physically (in main memory), elements
are allocated and placed consecutively
(row-wise), just like one-dimensional
arrays.
int array[2][2];
Introduction to Programming
Declaration
• Declaration
– size or number of elements should be
specified before compilation.
– only integer literals and preprocessor
constants are allowed.
#define ROW 10
#define COL 5
...
int array[5][10];
double d[ROW][COL];
...
Introduction to Programming
Initialization
• Initialization
#define ROW 4
#define COL 3
...
int array[2][2] = { {0,1},{2,3} };
int array1[2][2] = {0,1,2,3};
double array2[ROW][COL] = {0};
float array3[2][COL] = { {2},{3,4} };
...
Introduction to Programming
Accessing Elements
int array[2][3];
Introduction to Programming
An Important Note
Introduction to Programming
Array of Strings
Introduction to Programming
Example – 1/2
#include <stdio.h>
#include <string.h>
/* number of strings */
#define STRINGS 4
Introduction to Programming
Example – 2/2
int main()
{
char strings[STRINGS][MAX_CH]
= {“Ako”,
”si”,
”Wilmarc”,
”Lopez!”};
strcmp(strings[0], strings[1]);
strcat(strings[2], strings[3]);
return 0;
}
Introduction to Programming
Multi-Dimensional Arrays
• All of the discussed rules apply for N-
dimensional arrays.
int three_d[2][2][2] = { {{1,2},{3,4}},
{{5,6},{7,8}} };
float four_d[2][3][4][5];
int i,j,k,l;
for (i=0; i<2; i++)
for (j=0; j<3; j++)
for (k=0; k<4; k++)
for (l=0; l<5; l++)
four_d[i][j][k][l] = i*j*k*l;
Introduction to Programming
Arrays to Functions
• One-dimensional Arrays – size is not
required, hence, all array sizes will work.
void funxn( int array[], int size );
void funxn2( int array[SIZE] );
Introduction to Programming
Arrays to Functions
Introduction to Programming