Question

Add comments on this Fibonacci C++ program in detail. #include <iostream> using namespace std; int fib(int...

Add comments on this Fibonacci C++ program in detail.

#include <iostream>
using namespace std;

int fib(int n){
   int a = 0,b = 1,c;
   if(n == 0 || n == 1){
      return n;
   }
   while(n>2){
      c = b + a;
      a = b;
      b = c;
      n--;
   }
   return c;
}

int main(){
   int n;
   cout<<"Enter n: ";
   cin>>n;
   int result = fib(n);
   cout<<"Fib("<<n<<") = "<<result<<endl;
   return 0;
}
0 0
Add a comment Improve this question Transcribed image text
Answer #1
#include <iostream>

using namespace std;

int fib(int n) {
    int a = 0, b = 1, c;
    if (n == 0 || n == 1) { // if n is 0 or 1, then return n. because fibonacci of 0 is 0 and fibonacci of 1 is 1
        return n;
    }
    while (n > 2) { // as long as n is greater than 2
        // a and b are fibonacci numbers
        // set a to b
        // and set b to sum of previous two terms
        c = b + a;  // calculate fibonacci of next number. fibonacci of n is sum of previous two fibonacci numbers
        a = b;  // set a to b
        b = c;  // set b to sum of previous two terms which is stored in c
        n--;    // decrement value of n
    }
    return c;   // return the calculated fibonacci number 
}

int main() {
    int n;
    cout << "Enter n: ";    // ask user to enter a number
    cin >> n;   // read a number
    int result = fib(n);    // determine fibonacci of n 
    cout << "Fib(" << n << ") = " << result << endl;    // print fibonacci of n to screen
    return 0;
}

Add a comment
Know the answer?
Add Answer to:
Add comments on this Fibonacci C++ program in detail. #include <iostream> using namespace std; int fib(int...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT