Write a program in C++ to print an Array using Recursion

Static variables have the property of preserving their value even after they are out of their scope! Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.
Syntax:
static data_type var_name = var_value;
C++
#include <bits/stdc++.h>
using namespace std;
void print_array( int arr[], int size)
{
static int i;
if (i == size) {
i = 0;
cout << endl;
return ;
}
cout << arr[i] << " " ;
i++;
print_array(arr, size);
}
int main()
{
int arr[] = { 3, 5, 6, 8, 1 };
int n = sizeof (arr) / sizeof (arr[0]);
print_array(arr, n);
return 0;
}
|
2. Without using Static Variable
C++
#include <bits/stdc++.h>
using namespace std;
void print_array( int arr[], int size, int i)
{
if (i == size) {
cout << endl;
return ;
}
cout << arr[i] << " " ;
i++;
print_array(arr, size, i);
}
int main()
{
int arr[] = { 3, 5, 6, 8, 1 };
int n = sizeof (arr) / sizeof (arr[0]);
print_array(arr, n, 0);
return 0;
}
|
Time Complexity: O(n)
Auxiliary Space: O(1), If we consider recursive call stack then it would be O(n)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
19 Mar, 2023
Like Article
Save Article