fibonacci series

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • student
    New Member
    • Sep 2006
    • 3

    fibonacci series

    Hi guys,
    please tell me how to write the iterative version of fibonacci series using a stack.
    Thanks
  • D_C
    Contributor
    • Jun 2006
    • 293

    #2
    Why would you want to use a stack to to do the Fibonacci series? It takes two variables.

    The idea is to push 1 and 1 on to the stack to begin. Then, for each iteration, pop A, then B off the stack (B >= A). Push B+A, then B back on to the stack. Repeat that loop N times or so.

    The stack is entirely worthless, it could be just done using the two variables...

    Comment

    • student
      New Member
      • Sep 2006
      • 3

      #3
      I know the stack is entirely worthless but that's the assignment i have been given by my professor and I don't have a choice..
      I wrote this program:
      #include <cstdio>
      #include<iostre am>
      using namespace std;
      int main(int nNumberofArgs, char*pszArgs[])
      {
      int n;
      cout<<"n";
      cin>>n;
      int b=1, a=0, c=0;
      if (n == 0) cout <<a;
      else if (n==1)
      cout<<a<<b;
      else
      {
      //cout<<c=0;
      for (int i=1; i<=n; i++) {
      cout<<c;
      c=a+b;
      a=b;
      b=c;
      }
      }
      system("PAUSE") ;
      return 0;
      }


      but I don't know how to write it using a stack, I don't even know how to use push or pop functions...
      I would really appreciate ur help

      Comment

      • tyreld
        New Member
        • Sep 2006
        • 144

        #4
        I'm guessing you are probably supposed to define a stack class. Here is a one possible class definition for a stack (minus the actual member function implementations ).

        Code:
        #define STACK_SIZE 10
        
        Class Stack {
        public:[indent]Stack();
        
        void push(int value);
        int pop();
        [/indent]
        private:[indent]int size = STACK_SIZE;
        int count = 0;
        int stack[STACK_SIZE];
        [/indent]
        }

        Comment

        • D_C
          Contributor
          • Jun 2006
          • 293

          #5
          The stack is first in, last out. Suppose you push X, then Y.
          (last to come off stack) X Y (first to come off stack).

          Make a stack, say s. Before you start your loop, push 1 then 0, or 0 then 0, depending on how the numbers line up.

          For each iteration of your loop,
          Y = s.pop();
          X = s.pop();
          s.push(X+Y);
          s.push(X);

          When you get to N, you simply print s.pop(), assuming it lines up properly.

          Comment

          Working...