130 likes | 368 Views
COMP 102 Programming Fundamentals I. Presented by : Timture Choi. Introduction to Functions. Component used in structured programming E.g. “main()” function in C++ Used to solve the original problem Can be called more than one time Allow the code to be reused Overview: Input
E N D
COMP 102Programming Fundamentals I Presented by : Timture Choi
Introduction to Functions • Component used in structured programming • E.g. “main()” function in C++ • Used to solve the original problem • Can be called more than one time • Allow the code to be reused • Overview: • Input • Implementation • Output
C++ Functions • Internal • User-defined function • External • Provided by specialized library • Include the require header file • E.g. <iostream>, <math> • Call the function directly • E.g. cin, cout, abs, ceil, rand
Function Definition • Syntax: • E.g. <type> <function name>(<parameter list>) { <local declarations> <sequence of statements> <return statement (optional) } int absolute(int x){ if (x >= 0) return x; else return -x; }
Function Definition • Prototype • Return type • Function name • Parameter list • Function body • Variables/Constants declaration • Execution statements • Return value (optional) <type> <function name>(<parameter list>)
Function Call • Syntax: • <function name>(<argument list>); • <type> <var> = <function name>(<argument list>); • E.g. • int distance = absolute(-5);
Function Call • Note: • Function should be defined before used • Placed function definition in front of main() • Include function prototype before main() • Placed function definition after main() int absolute (int x) { … } int main(){ … } int absolute (int);// function prototype int main(){ … } int absolute(int x){ … }
Parameters/Arguments • E.g. • function(x, y) { … } • x, y are call the parameter • Parameter list • Describe the list of argument input to the function • If number of argument is more than 1 • <x, y> is the list of parameter
Return Value • Referred to the output of a function • If it is not a void function • Syntax: • return <expression>; • Data type from <expression> should be same as the function
Function Call • E.g. Step 1 2(a) 3 2(b) #include <iostream> using namespace std; double total_second(int, double ,double ); int main() { cout << total_second(1,1.5, 2) << endl; return 0; } double total_second( int hour, double minutes, double second) { return hour*3600 + minutes * 60 + second; }
SUMMARY • By the end of this lab, you should be able to: • Defined and invoke user-designed function