3D Array
A multidimensional array in C is essentially an array of arrays. The most common type is a 2D array, but you can have more dimensions, like 3D arrays or even higher.
Example:
Let’s say we are storing temperature data for a city over multiple weeks, where:
The first dimension represents the week.
The second dimension represents the day of the week.
The third dimension stores the temperature readings (morning, afternoon, evening).
#include <stdio.h> int main() { // 3 weeks, 7 days per week, 3 temperature readings per day int temperature[3][7][3] = { { {30, 32, 28}, {31, 33, 29}, {32, 34, 30}, {33, 35, 31}, {34, 36, 32}, {35, 37, 33}, {36, 38, 34} }, //week 1 { {28, 30, 26},{29, 31, 27}, {30, 32, 28}, {31, 33, 29}, {32, 34, 30}, {33, 35, 31}, {34, 36, 32} }, //week 2 { {27, 29, 25}, {28, 30, 26}, {29, 31, 27}, {30, 32, 28}, {31, 33, 29}, {32, 34, 30}, {33, 35, 31} } //week 3 }; // Display temperature readings for Week 1, Day 1 printf("Temperature readings for Week 1, Day 1:\n"); printf("Morning: %d°C, Afternoon: %d°C, Evening: %d°C\n", temperature[0][0][0], temperature[0][0][1], temperature[0][0][2]); return 0; }
Output:
Temperature readings for Week 1, Day 1: Morning: 30°C, Afternoon: 32°C, Evening: 28°C
Explanation:
We define a 3D array with dimensions [3][7][3]:
3 weeks
7 days per week
3 temperature readings per day (Morning, Afternoon, Evening)
Week 1:
Day | Temp 1 | Temp 2 | Temp 3 |
---|---|---|---|
Monday | 30 | 32 | 28 |
Tuesday | 31 | 33 | 29 |
Wednesday | 32 | 34 | 30 |
Thursday | 33 | 35 | 31 |
Friday | 34 | 36 | 32 |
Saturday | 35 | 37 | 33 |
Sunday | 36 | 38 | 34 |
Week 2:
Day | Temp 1 | Temp 2 | Temp 3 |
---|---|---|---|
Monday | 28 | 30 | 26 |
Tuesday | 29 | 31 | 27 |
Wednesday | 30 | 32 | 28 |
Thursday | 31 | 33 | 29 |
Friday | 32 | 34 | 30 |
Saturday | 33 | 35 | 31 |
Sunday | 34 | 36 | 32 |
Week 3:
Day | Temp 1 | Temp 2 | Temp 3 |
---|---|---|---|
Monday | 27 | 29 | 25 |
Tuesday | 28 | 30 | 26 |
Wednesday | 29 | 31 | 27 |
Thursday | 30 | 32 | 28 |
Friday | 31 | 33 | 29 |
Saturday | 32 | 34 | 30 |
Sunday | 33 | 35 | 31 |