Non recursively calculate fibonacci to n - C++ Data Structure

C++ examples for Data Structure:Algorithm

Description

Non recursively calculate fibonacci to n

Demo Code

#include <iostream>

int fibonacci(int);

int main(int argc, const char *argv[]) {
    int n;/*  ww  w .j  a  v a 2s. c  om*/

    std::cout << "Enter n: ";
    std::cin >> n;

    std::cout << "Fibonacci to the " << n << "th power: " << fibonacci(n) << std::endl;

    return 0;
}
// iteratively calculate fibonacci to n
int fibonacci(int n) {
    int fib;
    int firstTerm = 0;
    int secondTerm = 1;

    for (int i = 0; i < n; ++i) {
        // first two terms are 0 and 1
        if (i <= 1) {
            fib = i;
        } else {
            fib = firstTerm + secondTerm;

            firstTerm = secondTerm;
            secondTerm = fib;
        }
    }
    return fib;
}

Result


Related Tutorials