MSOE EE2905 / Mbed 2 deprecated Factorial_Function

Dependencies:   mbed

Fork of Factorial_Function by Sheila Ross

Files at this revision

API Documentation at this revision

Comitter:
rossatmsoe
Date:
Fri Sep 22 17:33:03 2017 +0000
Parent:
0:c8831b97b76a
Commit message:
Demonstrates use of function with returned value (including error codes)

Changed in this revision

main.cpp Show annotated file Show diff for this revision Revisions of this file
--- a/main.cpp	Fri Sep 22 15:48:50 2017 +0000
+++ b/main.cpp	Fri Sep 22 17:33:03 2017 +0000
@@ -1,39 +1,69 @@
-/*  Factorial
+/*  Factorial with Function
 
-Demonstrates the use of a for loop to compute a factorial, and use of scanf
+Demonstrates the use of function which returns a value or error code.
 
-Turn on local echo in your terminal application to see what you have typed
+Turn on local echo in your terminal application to see what you have typed.
 
 */
 
 #include "mbed.h"
 
+// We want to have our main function code first before the other functions.
+// However, we first need to list the first line (prototype header) of each
+// function we will call.
+
+int factorial(int n);
+
 Serial pc(USBTX,USBRX);
 
-int n;
 int main()
 {
+    int users_number;
+    int value;  // error codes could be negative, int same as long on our system
+
     while(1) {
 
         pc.printf("Enter the number (0 through 12):\n");
-        pc.scanf("%d",&n);
+        pc.scanf("%d",&users_number);
+
+        // Here, we call the function.
+
+        // The value of users_number will be deposited into the
+        // function's input variable n.
+
+        // The function returns an error code or the result of computation.
+        value=factorial(users_number);
+
+        // The case statement lets us treat error codes individually.
+        switch(value) {
+            case -1:
+                pc.printf("Number must be non-negative\n");
+                break;
+            case -2:
+                pc.printf("Number is too large\n");
+                break;
+            default:
+                pc.printf("%d!=%d\n",users_number,value);
+        }
 
-        if(n<0) {
-            pc.printf("Error:  Number must be non-negative\n");
-        } 
-        else {
-            if(n>12) {
-                pc.printf("Error:  Number is too large\n");
-            } 
-            else {
-                
-                unsigned long answer=1;
-                for(int k=1; k<=n; k++) {
-                    answer*=k;
-                }
-                pc.printf("%d!=%lu\n",n,answer);
+    }
+}
+
+int factorial(int n)
+{
+    int answer = 1;
+
+    if(n<0) {
+        return -1;
 
-            }
-        }
+    }  // We don't need an "else" because "return" takes us out of the function.
+    if(n>12) {         // We only get here if n>=0.
+        return -2;
     }
-}
\ No newline at end of file
+    for(int k=1; k<=n; k++) { // We only get here if n>=0 and n<=12.
+        answer*=k;
+    }
+
+    return answer;
+}
+