'How to traverse a 2D array using recursion

I'm looking for someone to help me to traverse and display the 2d array or matrix using recursion.

void display(int** matrix1,int row, int column)

This is what I am doing for the 1D array:

void print_array(int arr[], int size, int i)
{

    if (i == size) {
        cout << endl;
        return;
    }
    cout << arr[i] << " ";
    print_array(arr, size, i+1);
}

I know how to traverse 1D array but unable to do this. I want to display each element in the matrix using recursion.



Solution 1:[1]

First of all, it is not quite clear why you want a recursive solution. Perhaps it is a matter of tase, but I find recursion difficult to write, read and debug. Anyhow, I allowed myself to modify your 1d version:

#include <iostream>
#include <vector>

void print_array(const std::vector<int>& arr,size_t i = 0) {
    if (i == arr.size()) {
        std::cout << '\n';
        return;
    }
    std::cout << arr[i] << " ";
    print_array(arr, i+1);
}

I use size_t instead of int, because thats the type to be used when comparing with a containers size. I supplied a default for i because when you call it you dont want to pass the index, but just print the whole array. std::endl is not only printing a new line, but it also flushes the stream. This is unnecessary in most cases.

For the 2D case all you need to add is a second index and a condition to go to the next row.

That is, if the signature of the function is

void print_array(const std::vector<std::vector<int>>& arr,size_t i=0,size_t j=0)

and it prints arr[i][j] then you need to return without printing anything when i == arr.size() and you have to skip to the next row when j== arr[i].size(). This can be done with a condition along the line of:

    if (j == arr[i].size()) {
        std::cout << '\n';
        print_array( arr, i+1,0);  // start with the first element of next row
        return;
    }

PS is you insist on a int**, it should be straightforward to adapt, but I would strongly suggest to use a vector and perhaps even a std::vector<std::array> if the inner arrays all have same size.

Solution 2:[2]

Here is a simple recursive solution hope you can understand............

#include <iostream>
    using namespace std;
    
    
    void print(int x,int y,int arr[3][3])
    {
    
          cout<<arr[x][y]<<" ";
          if(x==2 && y==2)//Its a 3 by 3 matrix.....Index starts from 0 and ends at 2 for both row and colomn.
          {
              return;
          }
          else if(y==2)
          {
              cout<<endl;
              print(x+1,0,arr);
          }
          else
          print(x,y+1,arr);
    }
    int main()
    {
        int arr[3][3]={{1,2,3},{4,5,6},{7,8,9}};
        print(0,0,arr);
        return 0;
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Mahi Sarwar Anol