So far, every program you have written has included only one function, the required "main" function. Most larger C programs include many functions. This makes the programs much simpler to understand and much easier to change.
Create a project called "Operation". Create a source file called "Operation.c" and enter the following variation of your earlier program "Switcheroo.c":
/* Written by */#include <stdio.h>
/* Function prototypes */
float add(float a, float b);
float subtract(float a, float b);int main(void) {
char op;
float num1, num2, result;printf("? ");
scanf ("%f %c %f", &num1, &op, &num2);switch (op) {
case '+' :
result = add(num1, num2);
printf("%f\n\n", result);
break;case '-' :
result = subtract(num1, num2);
printf("%f\n\n", result);
break;default:
printf("I don't know how to %c\n\n", op);
break;}
return 0;
}
/* Function definitions */
float add(float a, float b) { return a + b; }
float subtract(float a, float b) { return a - b; }
This program includes three functions: main, add, and subtract. A function acts like a mysterious black box. You stick something into the box, it does something magical to it, and returns something back to you. A C function has several parts
float add(float a, float b) { return a + b; }
The declarations inside the parentheses tell C what inputs or parameters your function will be expecting. The type listed before the function tells C what type of output your function will return to the program which called it. The statements between the curly brackets are the body of the function. They tell C what the function will do with its parameters and how it will determine what to return to the program which called it. The curly brackets are required even when there is only one statement in the body of the function.
Since functions can be placed in any order in a C program, you should always include function prototypes at the top of your program. These prototypes tell C which functions you are using and how you expect them to be used. A function prototype is simply the function without its body.
Compile and run this program. Enter some simple expressions. This program should work exactly as did the one you ran earlier.
Change this program to handle multiplication and division. Make sure to check for division by zero and print an appropriate error message.