0

I would 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]; 
8
  • 1
    Could you elaborate on your comment "...the code used to work, now it doesn't"? It is difficult to help without knowing about your problem. Commented Nov 6, 2013 at 3:54
  • 1
    The posted code does not even compile. Commented Nov 6, 2013 at 3:55
  • 1
    Did you mean to make an array of 5 vectors or were you looking to have one vector with 5 items in it? Commented Nov 6, 2013 at 3:56
  • 1
    why don't you use l instead of n Commented Nov 6, 2013 at 3:57
  • Let me guess... Does it just give a stack overflow and print nothing? Commented Nov 6, 2013 at 3:59

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

-1
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]; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.