# [SOLVED] How to traverse a 2D array using recursion

## Issue

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

I am sure that you need to write a C program or a C++ program but using functionality of C due to your declaration of “2D array” like `int **`.:)

The function can be easy implemented if to use one more auxiliary recursive function.

Here is a demonstrative program

``````#include <stdio.h>

void display_row( int *a, size_t column )
{
column == 0 ? ( void )putchar( '\n' )
: ( void )( printf( "%2d ", *a ), display_row ( ++a, --column ) );
}

void display( int **a, size_t row, size_t column )
{
if ( row != 0 )
{
display_row( *a, column );
display( ++a, --row, column );
}
}

int main(void)
{
enum { M = 3, N = 4 };

int a1[N] = {  1,  2,  3,  4 };
int a2[N] = {  5,  6,  7,  8 };
int a3[N] = {  9, 10, 11, 12 };

int *a[M] = { a1, a2, a3 };

display( a, M, N );

return 0;
}
``````

The program output is

`````` 1  2  3  4
5  6  7  8
9 10 11 12
``````

If not to use an auxiliary function then another approach is to use a static variable inside the recursive function.

Here is a demonstrative program that uses a recursive function with a static variable.

``````#include <stdio.h>

void display( int** a, size_t row, size_t column )
{
static size_t pos = 0;

if ( row != 0 && column == 0 )
{
putchar( '\n' );
size_t tmp = column;
column = pos;
pos = tmp;
--row;
++a;
}

if ( row )
{
printf( "%2d ", a[pos++] );
display( a, row, --column );
}
}

int main(void)
{
enum { M = 3, N = 4 };

int a1[N] = {  1,  2,  3,  4 };
int a2[N] = {  5,  6,  7,  8 };
int a3[N] = {  9, 10, 11, 12 };

int *a[M] = { a1, a2, a3 };

display( a, M, N );

return 0;
}
``````

Its output is the same as shown above.

If you need a C++ program then just include headers

``````#include <iostream>
#include <iomanip>
``````

and instead of for example this call of printf

``````printf( "%2d ", a[pos++] );
``````

use

``````std::cout << std::setw( 2 ) << a[pos++];
``````