![](/media/cache/img/default_profile.jpg.50x50_q85.jpg)
Recursive version of fibonacci sequence
main.cpp@1:e11556a745d4, 2020-12-05 (annotated)
- Committer:
- saltire78
- Date:
- Sat Dec 05 12:56:50 2020 +0000
- Revision:
- 1:e11556a745d4
- Parent:
- 0:8f9265fb1552
.
Who changed what in which revision?
User | Revision | Line number | New contents of line |
---|---|---|---|
saltire78 | 1:e11556a745d4 | 1 | #include"mbed.h" //mbed header folder |
saltire78 | 0:8f9265fb1552 | 2 | |
saltire78 | 1:e11556a745d4 | 3 | Serial pc(USBTX,USBRX); //tx,rx |
saltire78 | 0:8f9265fb1552 | 4 | |
saltire78 | 1:e11556a745d4 | 5 | // create a function to generate a specific iteration value |
saltire78 | 1:e11556a745d4 | 6 | int fib(int iter){ |
saltire78 | 1:e11556a745d4 | 7 | if(iter == 0){ // when at the 1st base value return it (0) |
saltire78 | 1:e11556a745d4 | 8 | return 0; |
saltire78 | 1:e11556a745d4 | 9 | } |
saltire78 | 1:e11556a745d4 | 10 | else if(iter == 1) { // when at the 2nd base value return it (1) |
saltire78 | 1:e11556a745d4 | 11 | return 1; |
saltire78 | 1:e11556a745d4 | 12 | } |
saltire78 | 1:e11556a745d4 | 13 | else { |
saltire78 | 1:e11556a745d4 | 14 | return (fib(iter-1) + fib(iter-2)); // when at any subsequent fibannaci iteration return the sum of the 2 previous iterations |
saltire78 | 1:e11556a745d4 | 15 | } |
saltire78 | 0:8f9265fb1552 | 16 | } |
saltire78 | 1:e11556a745d4 | 17 | |
saltire78 | 1:e11556a745d4 | 18 | int main() { |
saltire78 | 1:e11556a745d4 | 19 | int i, iter; // define the unknown variables |
saltire78 | 1:e11556a745d4 | 20 | pc.printf("Number of iterations: "); // ask for number of iterations |
saltire78 | 1:e11556a745d4 | 21 | scanf("%d", &iter); // input number of iterations |
saltire78 | 1:e11556a745d4 | 22 | pc.printf("\n\rFibonacci Series(%d iterations): ",iter); // print statement |
saltire78 | 1:e11556a745d4 | 23 | |
saltire78 | 1:e11556a745d4 | 24 | for(i = 0;i<iter;i++) { // loop for all iterations |
saltire78 | 1:e11556a745d4 | 25 | pc.printf("%d ",fib(i)); // print the value of each given iteration |
saltire78 | 1:e11556a745d4 | 26 | } |
saltire78 | 1:e11556a745d4 | 27 | |
saltire78 | 1:e11556a745d4 | 28 | pc.printf("\n\n\r"); // cosmetic - moves the carriage to new line so if reset for further values it will be clearly seperate |
saltire78 | 1:e11556a745d4 | 29 | |
saltire78 | 1:e11556a745d4 | 30 | return 0; // close out the program |
saltire78 | 1:e11556a745d4 | 31 | } |