Interviews Questions, Algorithms, Aptitude, C Interview Program, C Theory Question, Aptitude Tricks, Test Series,

Wednesday, 27 March 2019

Fibonacci Series Algorithm

ALGORITHM F (n)

//Computes the nth Fibonacci number recursively by using its 

definition

//Input: A nonnegative integern

//Output: The nth Fibonacci number

if n ≤ 1 return n

else return F(n - 1) + F(n - 2)


 Other Method :

ALGORITHM Fib(n)

//Computes the nth Fibonacci number iteratively by using its definition
//Input: A nonnegative integer 
n


//Output: The nth Fibonacci number
F [0] ← 0;
 F [1] ← 1
for i ← 2 to n do
F [i] ← F [i - 1] + F [i - 2]
return F [n]


C program:


#include <stdio.h>
int main()
{
    int i, n, t1 = 0, t2 = 1, nextTerm;

    printf("Enter the number of terms: ");
    scanf("%d", &n);

    printf("Fibonacci Series: ");

    for (i = 1; i <= n; ++i)
    {
        printf("%d, ", t1);
        nextTerm = t1 + t2;
        t1 = t2;
        t2 = nextTerm;
    }
    return 0;

}


Output:

Enter the number of terms: 10
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34



0 comments:

Post a Comment