C++ Program to print an Array using Recursion

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

  1. Using static variable: Static variables have a 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; 
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // C++ Program to print
    // an Array using Recursion
      
    #include <bits/stdc++.h>
    using namespace std;
      
    // Recursive function to print the array
    void print_array(int arr[], int size)
    {
      
        // using the static variable
        static int i;
      
        // base case
        if (i == size) {
            i = 0;
            cout << endl;
            return;
        }
      
        // print the ith element
        cout << arr[i] << " ";
        i++;
      
        // recursive call
        print_array(arr, size);
    }
      
    // Driver code
    int main()
    {
      
        int arr[] = { 3, 5, 6, 8, 1 };
        int n = sizeof(arr) / sizeof(arr[0]);
      
        print_array(arr, n);
      
        return 0;
    }

    chevron_right

    
    

    Output:

    3 5 6 8 1
    
  2. Without using Static variable:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // C++ Program to print
    // an Array using Recursion
      
    #include <bits/stdc++.h>
    using namespace std;
      
    // Recursive function to print the array
    void print_array(int arr[], int size, int i)
    {
      
        // base case
        if (i == size) {
            cout << endl;
            return;
        }
      
        // print the ith element
        cout << arr[i] << " ";
        i++;
      
        // recursive call
        print_array(arr, size, i);
    }
      
    // Driver code
    int main()
    {
      
        int arr[] = { 3, 5, 6, 8, 1 };
        int n = sizeof(arr) / sizeof(arr[0]);
      
        print_array(arr, n, 0);
      
        return 0;
    }

    chevron_right

    
    

    Output:

    3 5 6 8 1
    


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.