An array is a collection of numbers(or of any other data-type), a 2d array is a collection of arrays but what is a 3d array?

A 3d array is a collection of 2d arrays. Imagine a 2d array as a matrix, then 3d array is a list of those 2d array matrices.

Imagine each element of a 1d array represents words on a page, then the 2d array represents a page and the 3d represents the whole book. For example, word[i][j][k]

Here ‘k’ refers to the index of that word and ‘j’ represents the page number and ‘i’ represents the book number, in case you are storing words written in a number of books.

Alternatively, a 3d array can also be imagined as a collection of points in a coordinate system with i,j,k as coordinates of those points.

Below is the code to take input and then print the elements of a 3d array. 

 Algorithm:

  1. First, we will take input from the user, the size of our 3d array (how many different books and maximum pages in each book and the maximum number of words on each page)
  2. Then we will run three for loops, each to increment each dimension of our array and then after setting a particular value for each dimension, we will store a value at that index.
  3. After that, we will run another three nested for loops in the same way but instead of storing this time, we will print that element.

Code:

#include <iostream>
using namespace std;

int main(){
	int a, b, c;
	cout << "Enter the Size of array\n";	//taking input for the size of array
	cin >> a >> b >> c;
	int arr[a][b][c];	//array of required size declared

	for (int i = 0; i < a; ++i)	//counter for first dimension
	{
		for (int j = 0; j < b; ++j)	//counter for second dimension
		{
			for (int k = 0; k < c; ++k)	//counter for third dimension
			{
				cout << "\nEnter value at position[" << i << "]" << "[" << j << "]" << "[" << k << "]";

				cin >> arr[i][j][k];	//taking input in the set counter
			}
		}
	}

	for (int i = 0; i < a; ++i)	//printing the array values as set
	{
		for (int j = 0; j < b; ++j)
		{
			for (int k = 0; k < c; ++k)
			{
				cout << "\nValue at position[" << i << "]" << "[" << j << "]" << "[" << k << "]= " << arr[i][j][k];
			}
		}
	}
	return 0;
}

Report Error/ Suggestion

Related Posts:

[yuzo_views]











CopyRight © 2020

CopyRight © 2020