What are Functions?
In general, we use (call) functions (aka: modules, methods, procedures, subprocedures, or subprograms) to perform a specific (atomic) task. In algebra, a function is defined as a rule or correspondence between values, called the function's arguments, and the unique value of the function associated with the arguments. For example:
If f(x) = 2x + 5, then f(1) = 7, f(2) = 9, and f(3) = 11 You would say the call f(1) returns the value 7 1, 2, and 3 are arguments 7, 9, and 11 are the resulting values (or corresponding values)Bjarne Stroustrup's C++ Glossary
functionName(argumentList)where the argumentList is a comma-separated list of arguments (data being sent into the function).
Using predefined functions:
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) cout << sqrt(100.0);// sqrt returns 10.0, which gets printed cout << 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 cout << sqrt(sqrt(625.0));
Using User-Defined functions:
//function prototype syntax: only data types (not names) of parameters must be specified functionType functionName(formal parameter list);
//Value-returning function definition syntax: including header and body functionType functionName(formal parameter list) //function header { //function body statements... //value-returning function return statement return expression; }
//function call syntax: x = functionName(actual parameter list); //Assignment, Output, Argument in another function call
x = functionName(); //Assignment, Output, Argument in another function call
//return statement syntax: return expression;
Program Execution: