Exercise 1
Exercise 1
Introduction
In C, [one-dimensional] arrays provide a mechanism to access a sequence of data using a single index,
such as item[0], item[1], item[2], .... Similarly, C supports the organization of data in a
table by specifying a row and a column:
The sample program 2D-array-with-proc.c shows a 2-dimensional array declared in main and passed
to a printArray function.
Altogether, two dimensional arrays are a wonderful way to store lots of data which would normally
require lots of arrays!
2D-array-with-proc.c
/* C program illustrating how 2-dimensional arrays
are passed in C
*/
#include <stdio.h>
int main ()
{
/* declare the 2-dimensional array */
int table [5][10];
int i, j; /* loop indices */
printArray (table);
return 0;
}
Exercise 1
1. The following program will not compile. Copy the program 2D-array.c and look over the various
array declarations.
2D-array.c
#include <stdio.h>
int main()
{
int i; // counter variables initialized to 0
} // main
The program is supposed to print out the sizes of each of the valid arrays and all of their rows
one by one. Note that an integer is 4 bytes, and arrays in the program are arrays of integers.
Thus, to find the size of an array the program multiplies how many integers are in the array by
the size of an integer, which is 4 bytes. This is why you get 4 times the number of things there
are in the array.
a. Which array declarations are invalid and are preventing the program from compiling? Do
you see a pattern of when it is invalid? Comment out the lines that are not working.
b. Write in comments next to each array what the size of the whole array is and what the
size of each row is?
c. How many elements does each array hold?
d. Write loops to display the contents of each array. You should use separate
nested for loops for each array.
e. Add another array, array6[][], which has the numbers (0, 1, 2, 3) in the first row, (2,
4, 6, 8) in the second row, and (3, 6, 9, 12) in the third row. Display the array once you
have declared and initialized it.