0

/* if i change line 10 to "print_array_1(a, n, ++i)" or "print_array_1(a, n, i+1)", then this code runs well.*/

#include<iostream>
#include<cstdio>
using namespace std;

void print_array_1(int a[], int n , int i)        // n = size of array,   i = start index
{
    if(i>=n) return;
    printf("%d\n",a[i]);
    print_array_1(a, n, i++);
}

int main()
{
    int arr[] = {1, 2, 3, 4, 5};
    int n = 5;
    print_array_1(arr, n, 0);
    return 0;
}

2 Answers2

1

Assuming this is C, you should use ++i. Why?

i++ increments i, but returns i. ++i increments i and returns 1+1.

With i++, you keep calling the recursion function with the same i value.

Community
  • 1
  • 1
Parker
  • 8,539
  • 10
  • 69
  • 98
0

i++ increments i after use in the call to print_array_1, so every call gets i=0.

bazzargh
  • 1,792
  • 10
  • 16
  • Here is more information about it: http://stackoverflow.com/questions/24853/what-is-the-difference-between-i-and-i – Esse Oct 25 '14 at 19:40