// Bob Myers -- functions2.cpp // // Example illustrating some function declarations, definitions, calls // // Better layout than functions1.cpp. This one has prototypes at the top #include #define TRUE 1 #define FALSE 0 // function PROTOTYPES listed here. int Sum(int x, int y, int z); double Average (double a, double b, double c); int InOrder(int x, int y, int z); // The prototypes above satisfy declare-before-use, so these functions can // be CALLED anywhere below this point. int main() { int i1, i2, i3; // integers for input double d1, d2, d3; // doubles for input double avg; // to compute average int total; // to compute the sum printf("Input three integers: "); scanf("%d %d %d", &i1, &i2, &i3); printf("Input three doubles: "); scanf("%lf %lf %lf", &d1, &d2, &d3); // samples of function calls total = Sum(i1, i2, i3); avg = Average(d1, d2, d3); printf("The sum of the three integers = %d\n", total); printf("The average of the three doubles = %f\n", avg); // note that we can place the call in the printf statements, which // prints the return values printf("The sum of 10, 14, and 18 = %d\n", Sum(10, 14, 18) ); printf("The average of 1.3, 2.7, and 6.9 = %f\n", Average(1.3, 2.7, 6.9) ); // Notice that we can pass in integers where doubles are expected // legal via automatic-type-conversion rules printf("The average of the three integers = %f\n", Average(i1, i2, i3) ); // Testing out the predicate function (InOrder) if (InOrder(i1, i2, i3)) printf("The three integers were typed in ascending order\n"); else printf("The three integers were NOT typed in ascending order\n"); return 0; } // function definitions can appear in any order, since the prototypes // were listed at the top to handle declare-before-use int Sum(int x, int y, int z) // add the three parameters together and return the result { int answer; answer = x + y + z; return answer; } double Average (double a, double b, double c) // add the parameters, divide by 3, and return the result { return (a + b + c) / 3.0; } int InOrder(int x, int y, int z) // answers yes/no to the question "are these parameters in order, // smallest to largest?" Returns TRUE (1) for yes, FALSE (0) for no. // (This kind of function often known as a "predicate function") { if (x <= y && y <= z) return TRUE; else return FALSE; }