codescracker
c++

C++ Program for Two Dimensional (2D) Array



« Previous Program Next Program »

In this article, you will learn and get code to implement two dimensional (2D) array in C++. Here are the list of programs on 2D array:

Note - A Two Dimensional (2D) array can be thought as of a matrix with rows and columns. For example:

1 2 3
4 5 6

is a two dimensional array of size, two rows and three columns.

Two Dimensional Array Program in C++

This program initializes 8 elements to a two-dimensional array of size four rows and two columns, then prints the array on output:

// C++ Program for Two Dimensional Array
// ---codescracker.com---

#include<iostream>
using namespace std;
int main()
{
    int arr[4][2] = {{1, 2}, {3, 4}, {5, 6}, {7, 8}};
    int i, j;
    cout<<"The Two-dimensional Array is:\n";
    for(i=0;  i<4; i++)
    {
        for(j=0; j<2; j++)
            cout<<arr[i][j]<<"  ";
        cout<<endl;
    }
    cout<<endl;
    return 0;
}

This program was build and run under Code::Blocks IDE. Here is its sample output:

two dimensional array in c++ programming

Note - The outer for loop is responsible for rows and the inner for loop is responsible for columns.

Get Array Elements from User of Given Size

Now this program allows user to enter the dimension or size of 2D array and then its elements of given size to store it in a 2D array arr[][] and print the array back on output screen along with index number (row and column number starting from 0):

// Two Dimensional (2D) Array Program in C++
// ---codescracker.com---

#include<iostream>
using namespace std;
int main()
{
    int row, col, i, j, arr[10][10];
    cout<<"Enter the Row and Column Size for Array: ";
    cin>>row>>col;
    cout<<"Enter "<<row*col<<" Array Elements: ";
    for(i=0; i<row; i++)
    {
        for(j=0; j<col; j++)
            cin>>arr[i][j];
    }
    cout<<"\nThe Array is:\n";
    for(i=0; i<row; i++)
    {
        for(j=0; j<col; j++)
            cout<<arr[i][j]<<"  ";
        cout<<endl;
    }
    cout<<"\nArray Elements with its Index:\n";
    for(i=0; i<row; i++)
    {
        for(j=0; j<col; j++)
            cout<<"arr["<<i<<"]["<<j<<"] = "<<arr[i][j]<<"  ";
        cout<<endl;
    }
    cout<<endl;
    return 0;
}

The snapshot given below shows the initial output produced by this program:

c++ two dimensional array program

Now supply inputs say 3 as row and 4 as column size of the array, then 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2 as 12 elements for the array:

c++ program 2d array

Same Program in Other Languages

C++ Online Test


« Previous Program Next Program »



© Copyright 2021. All Rights Reserved.

CodesCracker