Array of Arrays

If you have several arrays, you can combine them into an array of arrays. This is a large array that consists of two or more small arrays.

For example, let’s say I have two arrays, each with three elements:

first[3] = { 11, 17, 23 };
second[3] = { 46, 68, 82 };

Each array has 3 elements. Now I can combine these 2 arrays into an array of arrays:

combo[2][3] = {

{ 11, 17, 23 },{ 46, 68, 82 }};

My combo array has 2 arrays, with 3 elements in each array. This is an array of arrays.

Sample Array of Arrays

Let’s try an array of arrays, to print a table of data on the screen. Remember the volcanic eruptions recorded in the GRIP ice cores, from our program erupt.c? Well, we can add another set of information (about the bubonic plague) and create a rather scary chart.

During the Dark Ages, the bubonic plague ravaged Africa, the Middle East, Europe, and Asia. Four of these outbreaks were in the same centuries as the massive volcanic eruptions recorded in the GRIP ice cores.

In this script, we will write a separate array for each century, then combine them into an array of arrays.

#include<stdio.h>
void main( )
{
int i;
int years[2][4] = { 

{ 536, 626, 934, 1258 },
{ 540, 635, 965, 1270 }

};
printf(“\nThe Dark Ages were difficult times:”);
printf(“\nVolcano\t\tPlague”);
for(i = 0; i < 4; i++)

printf(“\n%d AD\t\t%d AD”, years[0][i], years[1][i]);
printf(“\nI’m glad I didn’t live during the Dark Ages!\n”);
 

Save your source code as darkages.c. Compile it. Link it. Run it.

This program loops through each element of the array of arrays, and prints this:

The Dark Ages were difficult times:

Volcano
536 AD
626 AD
934 AD
1258 AD
Plague
540 AD
635 AD
965 AD
1270 AD

The most important line in this script is:

printf(“\n%d AD\t\t%d AD”, years[0][i], years[1][i]);

Here is what each piece of this line means:

  1. printf(“\n%d AD\t\t%d AD” — this means to print a year AD, then tab twice, then print another year AD
  2. years[0][i] — this means to go to the first array (index 0) and print the current element (in the loop)
  3. years[1][i] — this means to go to the second array (index 1) and print the current element (in the loop)

This results in the beautiful (but scary) array of volcanoes and plagues in the Dark Ages.

 

Published by Michael Boguslavskiy

Michael Boguslavskiy is a full-stack developer & online presence consultant based out of New York City. He's been offering freelance marketing & development services for over a decade. He currently manages Rapid Purple - and online webmaster resources center; and Media Explode - a full service marketing agency.

Leave a comment

Your email address will not be published. Required fields are marked *