Home C Programming Tutorial C++ program to access an element in 2-D Array

C++ program to access an element in 2-D Array

by Ankit Chauhan
20 minutes read

In this article, you’ll learn how to make C++ program to access an element in 2-D Array with explanation.

What is an Array?

An array is a collection of similar data elements stored at contiguous memory locations. It is the simplest data structure where each data element can be accessed directly by only using its index number.

What is Two Dimensional Array

Two Dimensional Arrays can be thought of as an array of arrays or as a matrix consisting of rows and columns.

Following is an example of a 2D array:

9378
32345

This array has 2 rows and 3 columns.

A two-dimensional array in C++ will follow zero-based indexing, like all other arrays in C++.

C++ program to access an element in a 2-D array

#include <iostream>

using namespace std;

int main() {
  // Declare and initialize a 2-D array with 3 rows and 4 columns
  int arr[3][4] = {
    {1, 2, 3, 4},
    {5, 6, 7, 8},
    {9, 10, 11, 12}
  };

  // Access an element in the 2-D array
  int row = 1;
  int col = 2;
  int element = arr[row][col];

  // Output the element to the console
  cout << "The element at row " << row << " and column " << col << " is: " << element << endl;

  return 0;
}

In this program, we first declare and initialize a 2-D array arr with 3 rows and 4 columns. We then choose a row and column to access an element from the array. In this example, we choose row 1 (which is the second row, since arrays are 0-indexed) and column 2 (which is the third column). We then access the element using the syntax arr[row][col] and store it in a variable called element. Finally, we output the element to the console using the cout statement.

Note that in a 2-D array, the first index (row) specifies the row number and the second index (column) specifies the column number. Also, remember that arrays in C++ are 0-indexed, meaning that the first element of an array has an index of 0, the second element has an index of 1, and so on.

The output of the above program will be

The element at row 1 and column 2 is: 7

This is because we accessed the element at row 1 and column 2 of the 2-D array arr, which has the value 7. We then output this value to the console using the cout statement in the program.

related posts

Leave a Comment

Enable Notifications OK No thanks