Demonstrates use of function with returned value (including error codes)

Dependencies:   mbed

Fork of Factorial_Function by Sheila Ross

main.cpp

Committer:
rossatmsoe
Date:
2017-09-22
Revision:
1:e6e33adba30e
Parent:
0:c8831b97b76a

File content as of revision 1:e6e33adba30e:

/*  Factorial with Function

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.

*/

#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 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",&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);
        }

    }
}

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;
    }
    for(int k=1; k<=n; k++) { // We only get here if n>=0 and n<=12.
        answer*=k;
    }

    return answer;
}