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 ≤ return n

else return F(n 1F(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
[0] ← 0;
 [1] ← 1
for ← to do
[i← [1] [2]
return [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