Recursive version of fibonacci sequence

Dependencies:   mbed

Files at this revision

API Documentation at this revision

Comitter:
saltire78
Date:
Sat Dec 05 12:56:50 2020 +0000
Parent:
0:8f9265fb1552
Commit message:
.

Changed in this revision

main.cpp Show annotated file Show diff for this revision Revisions of this file
diff -r 8f9265fb1552 -r e11556a745d4 main.cpp
--- a/main.cpp	Fri Jul 31 12:19:03 2020 +0000
+++ b/main.cpp	Sat Dec 05 12:56:50 2020 +0000
@@ -1,20 +1,31 @@
-#include"mbed.h"
+#include"mbed.h"                                                                //mbed header folder
 
-Serial pc(USBTX,USBRX);//tx,rx
-PwmOut led(LED1);
-float brightness=0.0;
+Serial pc(USBTX,USBRX); //tx,rx
 
-int main(){
-    pc.printf("Press 'u' to turn LED1 brightness up, 'd' to turn it down\n");
-    while(1){
-        char c =pc.getc();
-        if((c=='u')&&(brightness<0.5)){
-            brightness+=0.01;
-            led=brightness;
-            pc.putc('^');}
-        if((c=='d')&&(brightness>0.0)){
-            brightness-=0.01;
-            led=brightness;
-            pc.putc('v');}
-    }
+// 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
+}
\ No newline at end of file