Recursive version of fibonacci sequence

Dependencies:   mbed

main.cpp

Committer:
saltire78
Date:
2020-12-05
Revision:
1:e11556a745d4
Parent:
0:8f9265fb1552

File content as of revision 1:e11556a745d4:

#include"mbed.h"                                                                //mbed header folder

Serial pc(USBTX,USBRX); //tx,rx

// create a function to generate a specific iteration value
int fib(int iter){          
    if(iter == 0){                                                              // when at the 1st base value return it (0)
        return 0;
   } 
    else if(iter == 1) {                                                        // when at the 2nd base value return it (1)
        return 1;
   } 
    else {
        return (fib(iter-1) + fib(iter-2));                                     // when at any subsequent fibannaci iteration return the sum of the 2 previous iterations
   }
}

int main() {
    int i, iter;                                                                // define the unknown variables
    pc.printf("Number of iterations: ");                                        // ask for number of iterations
    scanf("%d", &iter);                                                         // input number of iterations
    pc.printf("\n\rFibonacci Series(%d iterations): ",iter);                    // print statement
    
    for(i = 0;i<iter;i++) {                                                     // loop for all iterations
        pc.printf("%d ",fib(i));                                                // print the value of each given iteration
   }
   
    pc.printf("\n\n\r");                                                        // cosmetic - moves the carriage to new line so if reset for further values it will be clearly seperate

    return 0;                                                                   // close out the program
}