Two dimensional array in cpp

C++ Multi-Dimensional Arrays

To declare a multi-dimensional array, define the variable type, specify the name of the array followed by square brackets which specify how many elements the main array has, followed by another set of square brackets which indicates how many elements the sub-arrays have:

As with ordinary arrays, you can insert values with an array literal — a comma-separated list inside curly braces. In a multi-dimensional array, each element in an array literal is another array literal.

Each set of square brackets in an array declaration adds another dimension to an array. An array like the one above is said to have two dimensions.

Arrays can have any number of dimensions. The more dimensions an array has, the more complex the code becomes. The following array has three dimensions:

Access the Elements of a Multi-Dimensional Array

To access an element of a multi-dimensional array, specify an index number in each of the array’s dimensions.

This statement accesses the value of the element in the first row (0) and third column (2) of the letters array.

Читайте также:  Python init self master

Example

Remember that: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

Change Elements in a Multi-Dimensional Array

To change the value of an element, refer to the index number of the element in each of the dimensions:

Example

Loop Through a Multi-Dimensional Array

To loop through a multi-dimensional array, you need one loop for each of the array’s dimensions.

The following example outputs all elements in the letters array:

Example

This example shows how to loop through a three-dimensional array:

Example

Why Multi-Dimensional Arrays?

Multi-dimensional arrays are great at representing grids. This example shows a practical use for them. In the following example we use a multi-dimensional array to represent a small game of Battleship:

Example

// Keep track of how many hits the player has and how many turns they have played in these variables
int hits = 0;
int numberOfTurns = 0;

// Allow the player to keep going until they have hit all four ships
while (hits < 4) int row, column;

// Check if a ship exists in those coordinates
if (ships[row][column]) // If the player hit a ship, remove it by setting the value to zero.
ships[row][column] = 0;

// Increase the hit counter
hits++;

// Tell the player that they have hit a ship and how many ships are left
cout > else // Tell the player that they missed
cout >

// Count how many turns the player has taken
numberOfTurns++;
>

Источник

C++ Multi-dimensional Arrays

The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size x,y, you would write something as follows −

Where type can be any valid C++ data type and arrayName will be a valid C++ identifier.

A two-dimensional array can be think as a table, which will have x number of rows and y number of columns. A 2-dimensional array a, which contains three rows and four columns can be shown as below −

Two Dimensional Arrays

Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in a.

Initializing Two-Dimensional Arrays

Multidimensioned arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row have 4 columns.

int a[3][4] = < , /* initializers for row indexed by 0 */ , /* initializers for row indexed by 1 */ /* initializers for row indexed by 2 */ >;

The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to previous example −

Accessing Two-Dimensional Array Elements

An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and column index of the array. For example −

The above statement will take 4 th element from the 3 rd row of the array. You can verify it in the above digram.

#include using namespace std; int main () < // an array with 5 rows and 2 columns. int a[5][2] = < , , , ,>; // output each array element's value for ( int i = 0; i < 5; i++ ) for ( int j = 0; j < 2; j++ ) < cout return 0; >

When the above code is compiled and executed, it produces the following result −

a[0][0]: 0 a[0][1]: 0 a[1][0]: 1 a[1][1]: 2 a[2][0]: 2 a[2][1]: 4 a[3][0]: 3 a[3][1]: 6 a[4][0]: 4 a[4][1]: 8

As explained above, you can have arrays with any number of dimensions, although it is likely that most of the arrays you create will be of one or two dimensions.

Источник

Two Dimensional Array in C++

Two Dimensional Array in C++

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Introduction

2D Array Representation

A two-dimensional array in C++ is the simplest form of a multi-dimensional array. It can be visualized as an array of arrays. The image below depicts a two-dimensional array. A two-dimensional array is also called a matrix. It can be of any type like integer, character, float, etc. depending on the initialization. In the next section, we are going to discuss how we can initialize 2D arrays.

Initializing a 2D array in C++

int arr[4][2] =  1234, 56>, 1212, 33>, 1434, 80>, 1312, 78> > ; 

So, as you can see, we initialize a 2D array arr , with 4 rows and 2 columns as an array of arrays. Each element of the array is yet again an array of integers. We can also initialize a 2D array in the following way.

int arr[4][2] = 1234, 56, 1212, 33, 1434, 80, 1312, 78>; 

Printing a 2D Array in C++

We are done initializing a 2D array, now without actually printing the same, we cannot confirm that it was done correctly. Also, in many cases, we may need to print a resultant 2D array after performing some operations on it. So how do we do that? The code below shows us how we can do that.

#include using namespace std; main( )  int arr[4][2] =   10, 11 >,  20, 21 >,  30, 31 >,  40, 41 > > ; int i,j; cout<"Printing a 2D Array:\n"; for(i=0;i4;i++)  for(j=0;j2;j++)  cout<"\t"[i][j]; > cout; > > 

Printing A 2D Array

Output: In the above code,

  • We firstly initialize a 2D array, arr[4][2] with certain values,
  • After that, we try to print the respective array using two for loops,
  • the outer for loop iterates over the rows, while the inner one iterates over the columns of the 2D array,
  • So, for each iteration of the outer loop, i increases and takes us to the next 1D array. Also, the inner loop traverses over the whole 1D array at a time,
  • And accordingly, we print the individual element arr[ i ][ j ] .

Taking 2D Array Elements As User Input

Previously, we saw how we can initialize a 2D array with pre-defined values. But we can also make it a user input too. Let us see how

#include using namespace std; main( )  int s[2][2]; int i, j; cout<"\n2D Array Input:\n"; for(i=0;i2;i++)  for(j=0;j2;j++)  cout<"\ns["<"]["<"]= "; cin>>s[i][j]; > > cout<"\nThe 2-D Array is:\n"; for(i=0;i2;i++)  for(j=0;j2;j++)  cout<"\t"[i][j]; > cout; > > 

2D Array User Input

For the above code, we declare a 2X2 2D array s . Using two nested for loops we traverse through each element of the array and take the corresponding user inputs. In this way, the whole array gets filled up, and we print out the same to see the results.

Matrix Addition using Two Dimensional Arrays in C++

As an example let us see how we can use 2D arrays to perform matrix addition and print the result.

#include using namespace std; main()  int m1[5][5], m2[5][5], m3[5][5]; int i, j, r, c; cout<"Enter the no.of rows of the matrices to be added(max 5):"; cin>>r; cout<"Enter the no.of columns of the matrices to be added(max 5):"; cin>>c; cout<"\n1st Matrix Input:\n"; for(i=0;ir;i++)  for(j=0;jc;j++)  cout<"\nmatrix1["<"]["<"]= "; cin>>m1[i][j]; > > cout<"\n2nd Matrix Input:\n"; for(i=0;ir;i++)  for(j=0;jc;j++)  cout<"\nmatrix2["<"]["<"]= "; cin>>m2[i][j]; > > cout<"\nAdding Matrices. \n"; for(i=0;ir;i++)  for(j=0;jc;j++)  m3[i][j]=m1[i][j]+m2[i][j]; > > cout<"\nThe resultant Matrix is:\n"; for(i=0;ir;i++)  for(j=0;jc;j++)  cout<"\t"[i][j]; > cout; > > 

Matrix Addition Using 2D Arrays

  • We take two matrices m1 and m2 with a maximum of 5 rows and 5 columns. And another matrix m3 in which we are going to store the result,
  • As user inputs, we took the number of rows and columns for both the matrices. Since we are performing matrix addition, the number of rows and columns should be the same for both the matrices,
  • After that, we take both the matrices as user inputs, again using nested for loops,
  • At this point, we have both the matrices m1 and m2,
  • then we traverse through the m3 matrix, using two for loops and update the respective elements m3[ i ][ j ] by the value of m1[i][j]+m2[i][j] . In this way, by the end of the outer for loop, we get our desired matrix,
  • At last, we print out the resultant matrix m3.

Pointer to a 2D Array in C++

If we can have a pointer to an integer, a pointer to a float, a pointer to a char, then can we not have a pointer to an array? We certainly can. The following program shows how to build and use it.

#include using namespace std; /* Usage of pointer to an array */ main( )  int s[5][2] =  1, 2>, 1, 2>, 1, 2>, 1, 2> > ; int (*p)[2] ; int i, j; for (i = 0 ; i  3 ; i++)  p=&s[i]; cout<"Row"<":"; for (j = 0; j  1; j++) cout<"\t"<*(*p+j); cout; > > 

2D Array Pointer

  • In the above code, we try to print a 2D array using pointers,
  • As we earlier did, at first we initialize the 2D array, s[5][2] . And also a pointer (*p)[2] , where p is a pointer which stores the address of an array with 2 elements,
  • As we already said, we can break down a 2D array as an array of arrays. So in this case, s is actually an array with 5 elements, which further are actually arrays with 2 elements for each row.
  • We use a for loop to traverse over these 5 elements of the array, s. For each iteration, we assign p with the address of s[i] ,
  • Further, the inner for loop prints out the individual elements of the array s[i] using the pointer p. Here, (*p + j) gives us the address of the individual element s[i][j], so using *(*p+j) we can access the corresponding value.

Passing 2-D Array to a Function

In this section, we are going to learn how to pass a 2D array to any function and access the corresponding elements. In the code below, we pass the array a, to two functions show() and print() which prints out the passed 2D array.

#include using namespace std; void show(int (*q)[4], int row, int col)  int i, j ; for(i=0;irow;i++)  for(j=0;jcol;j++) cout<"\t"<*(*(q + i)+j); cout<"\n"; > cout<"\n"; > void print(int q[][4], int row, int col)  int i, j; for(i=0;irow;i++)  for(j=0;jcol;j++) cout<"\t"[i][j]; cout<"\n"; > cout<"\n"; > int main()  int a[3][4] =  10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21> ; show (a, 3, 4); print (a, 3, 4); return 0; > 

2D Array To Functions

  • In the show( ) function we have defined q to be a pointer to an array of 4 integers through the declaration int (*q)[4] ,
  • q holds the base address of the zeroth 1-D array
  • This address is then assigned to q, an int pointer, and then using this pointer all elements of the zeroth 1D array are accessed.
  • Next time through the loop when i takes a value 1, the expression q+i fetches the address of the first 1-D array. This is because q is a pointer to the zeroth 1-D array and adding 1 to it would give us the address of the next 1-D array. This address is once again assigned to q and using it all elements of the next 1-D array are accessed
  • In the second function print() , the declaration of q looks like this: int q[][4] ,
  • This is same as int (*q )[4], where q is a pointer to an array of 4 integers. The only advantage is that we can now use the more familiar expression q[i][j] to access array elements. We could have used the same expression in show() as well but for better understanding of the use of pointers, we use pointers to access each element.

Conclusion

So, in this article, we discussed two-dimensional arrays in C++, how we can perform various operations as well as its application in matrix addition. For any further questions feel free to use the comments.

References

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Оцените статью