fibonacci series code code example

Example 1: fibonacci series

// Fibonacci Series
0,1,1,2,3,5,8,13,21,34,55,89,144......

Example 2: fibonacci series in c

#include <stdio.h>
int main() {
    int t1 = 0, t2 = 1, nextTerm = 0, n;
    printf("Enter a positive number: ");
    scanf("%d", &n);

    // displays the first two terms which is always 0 and 1
    printf("Fibonacci Series: %d, %d, ", t1, t2);
    nextTerm = t1 + t2;

    while (nextTerm <= n) {
        printf("%d, ", nextTerm);
        t1 = t2;
        t2 = nextTerm;
        nextTerm = t1 + t2;
    }

    return 0;
}

Example 3: Fibonacci series

//to find nth fibonacci number(recursive solution)
class Solution {
    public int fib(int n) {
     if(n==0){
         return 0;
     }
        if(n==1){
            return 1;
        }
        if(n==2){
            return 1;
        }
        return fib(n-1)+fib(n-2);
    }
}

Tags:

C Example