f(x) = 2x + 5In mathematics, the symbol 'x' is a placeholder, and when you run the function for a value, you "plug in" the value in place of x. Consider the following equation, which we then simplify:
y = f(10) // must evaluate f(10) y = 2 * 10 + 5 // plug in 10 for x y = 20 + 5 y = 25 // so f(10) gives the answer 25In programming, we would say that the call f(10) returns the value 25.
functionName(argumentList)where the argumentList is a comma-separated list of arguments (data being sent into the function). Use the call anywhere that the returned answer would make sense.
double x = 9.0, y = 16.0, z;
z = sqrt(36.0); // sqrt returns 6.0 (gets stored in z)
z = sqrt(x); // sqrt returns 3.0 (gets stored in z)
z = sqrt(x + y); // sqrt returns 5.0 (gets stored in z)
printf("%f\n", sqrt(100.0)); // sqrt returns 10.0, which gets printed
printf("%f\n", sqrt(49)); // because of automatic type conversion rules
// we can send an int where a double is
// expected. This call returns 7.0
// in this last one, sqrt(625.0) returns 25.0, which gets sent as the
// argument to the outer sqrt call. This one returns 5.0, which gets
// printed
printf("%f\n", sqrt(sqrt(625.0)) );
Try this code here
#include <stdio.h> // common I/O routines #include <math.h> // common math functions #include <stdlib.h> // common general C functions #include <ctype.h> // character manipulation functions
return-type function-name( parameter-list );
// GOOD function prototypes int Sum(int x, int y, int z); double Average (double a, double b, double c); int InOrder(int x, int y, int z); int DoTask(double a, char letter, int num); double Average (double, double, double); // Note: no parameter names here // okay on a declaration // BAD prototypes (i.e. illegal) double Average(double x, y, z); // Each parameter must list a type PrintData(int x); // missing return type int Calculate(int) // missing semicolon int double Task(int x); // only one return type allowed!
return-type function-name( parameter-list )
{
function-body (declarations and statements)
}
return expression;
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 for yes, false for no.
{
if (x <= y && y <= z)
return 1;
else
return 0;
}
char GetALetter(); // no parameters void PrintQuotient(int x, int y); // void return type void KillSomeTime(); // both