Furqan_25
Furqan_25

Reputation: 19

is there a preference to coding Fibonacci sequence

Basically my professor coded it another way but mine works too. I just wanted to ask is there any hidden problems in my code that I don't understand? If it's basically the same (which I'm assuming it is), I'll just do it my way.

MY CODE

int current=0, next =1, temp;
  for(int i=0;i<number;i++){
    temp = current;
    current = next;
    next +=temp;
  }
  return current;
}

PROFESSOR CODE

  int current=0, next =1, temp;
  for(int i=0;i<number;++i){
    temp = next+current;
    current = next;
    next =temp;
  }
  return current;
}

Upvotes: 0

Views: 89

Answers (2)

lancegerday
lancegerday

Reputation: 762

Both implementations are functionally identical. Just use whichever you find more readable.

Upvotes: 0

cigien
cigien

Reputation: 60228

In general, the compiler will do a great job of generating optimal assembly, so I would suggest writing your code in the most readable way possible.

Here's one way of writing it that should be quite readable:

int current = 0, next = 1;

for(int i = 0; i < number; ++i )
  current = std::exchange(next, current + next);

return current;

Once you understand how std::exchange works, this should be much clearer. e.g. there's no need for a temp variable at all.

Upvotes: 4

Related Questions