# recursive stuff dudes

• 10-02-2004
drdodirty2002
recursive stuff dudes
check out the following piece of code friends
Code:

```#include<iostream> #include<string> int fibonacci(int a); using namespace std; template <class T, int n> class stack { private: T elt[n]; int counter; public: void clearstack() { counter = -1;                }  //INITIALIZE COUNTER bool emptystack() { return counter==-1?true:false;} //EVALUATION IF STACK IS EMPTY bool fullstack()  { return counter==n-1?true:false; } //EVALUATION IF STACK IS FULL void push(T x)    { counter++; elt[counter] = x; } //FUNCTION TO ADD TO STACK T pop()          { T x; x= elt[counter];counter--;return x; } //FUNCTION TO POP THE STACK }; void main() {                 int d,v;                         cout<<"ENTER THE NUMBER FOR THE FIBONACCI SERIES: "<<"\n";         cin>>v;         d= fibonacci(v); cout<<d; }   int fibonacci(int v) {         stack <int, 15> s;         int counter=0;         int y=0;         int z=0;         int res=0;         s.clearstack();                 s.push(1);                 s.push(1); if(v==0) return 1; else if(v==counter)         {         y=s.pop();         z=s.pop();         res=y+z;         return res;         } else if(v>counter)         {                                y=s.pop();                 z=s.pop();                 res=y + z;                 ++counter;                 return res + fibonacci(res - y);                 .         } return 0; }```
I get a freaky error message that says unhandeled exception every time I attempt to run it. Do any of you see a problem here. Any ideas here
• 10-02-2004
MrWizard
counter is a local variable in your fib function. So everytime you enter that function it is always zero. So the check 'v>counter' is usually going to be evaluated to true. That is why it is crushing your stack.
• 10-02-2004
bithub
res is always going to equal 2, and res-y is always going to equal 1. Basically you are calling fibonacci(1) until your stack dies.