Mithun Biswas
Mithun Biswas

Reputation: 43

This recursive function become infinite loop. Why?

/* 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;
}

Upvotes: 0

Views: 72

Answers (2)

Parker
Parker

Reputation: 8851

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.

Upvotes: 1

bazzargh
bazzargh

Reputation: 1842

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

Upvotes: 0

Related Questions