0

I will like some help, the code used to work, now it doesn't. Help. The purpose is for the user to see the vector backwards using a recursion.

int listar(int v[5], int l); 

void main(){ 
    int vector[5]={1,2,3,4,5}; 
    listar(vector,-1); 
} 

int listar(int v[5],int l){ 
    int n=0; 
    if (n<=5){ 
        cout<< listar(v, n+1)<< endl; 
    return v[n]; 
    } 
return v[5]; 
NVG
  • 19
  • 1
  • 2

4 Answers4

0

In the method int listar(int v[5],int l){ you are not using the parameter l at all. Shouldn't the code be using that instead of making n=0 in each recursive call.

Pai
  • 282
  • 2
  • 3
0

The code is recursive, You have listar being called by listar.

Recursion is fine, but as you always set n to 0, and then say "if n<5", then you'll get infinite recursion.

I think this is what you mean:

int vector[5]={1,2,3,4,5}; 
    listar(vector,0); 
} 

int listar(int v[5],int l){  
    if (l<=5){ 
        cout<< listar(v, l+1)<< endl;
    }
    return v[l]; 

But this is quite different

binderbound
  • 791
  • 1
  • 7
  • 27
0

This works,

int listar(int v[],int index);

int main(){ 
    int vector[5]={1,2,3,4,5}; 
    listar(vector,(sizeof(vector)/sizeof(*vector))-1); 
    system("pause");
    return 0;
} 

int listar(int v[],int index)
{
    if(index<0) return -1;
    cout<<v[index]<<"\n";
    listar(v,index-1);
    return v[index];
}

Note: You should always use int main as the signature of main function.

Community
  • 1
  • 1
mehmet mecek
  • 2,615
  • 2
  • 21
  • 25
0
int listar(vector<int> v, int l); 

int main(){ 
    vector<int> v;
    v.push_back(0);
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    v.push_back(4);
    v.push_back(5);
    listar(v,-1); 
    return 0;
} 

int listar(vector<int> v,int n){ 
    if (n<5){ 
        cout<< listar(v, n+1)<< endl; 
    return v[n]; 
    } 
return v[5]; 
}