Series Printing coding 4

CODE NO:- 16

Q)Write a program to display the Fibonnaci series 0,1,1,2,3,5,8,13,21.....

#LOGIC
Here we need to add the two previous term to get next term.

NOTE: Considering starting index as 0 (zero).

For example: we got 1 by adding 1 and 0 i.e we got 2nd term by adding  1st term and 0th term.

#Program (In C):

In  C language we use  ' // '  for Single line comment and /*---*/ for multi line comment

APPROACH 1: Using RECURSION

#include<stdio.h> int fibo(int); // function prototype void main() { int n,i; printf("\n enter no.of terms:"); scanf("%d",&n); for(i=0;i<n;i++) { printf("%d, ",fibo(i)); // function call } return 0; } int fibo(int a) // function body { if(a==0) return 0; else if(a==1) return 1; else return fibo(a-1)+fibo(a-2); // recursive call }

We got this output by using DEV C++ (IDE)


APPROACH 2: Using LOOP

#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 =0; i<n; ++i)

{
        printf("%d, ", t1);
        nextTerm = t1 + t2;
        t1 = t2;
        t2 = nextTerm;
    }
    return 0;
}

We got this output by using DEV C++ (IDE)




Comments

Popular posts from this blog

WHY PROGRAMMING?

Series code 2

Pattern Printing coding 7