4.3 Functions
Functions Last class we talked about the idea and organization of a function. Today we talk about how to program them
Function Prototype FUNCTIONTYPE FUCNTIONNAME(TYPE FOR VAR1,TYPE FOR VAR 2……); Example int FindSum(int, int );
Function Prototype Used to let the computer know function return type and parameters before the function runs. Best to place at the very top of a program immediately after header files
Function Definition FUCNTIONTYPE FUNCTIONNAME(TYPE PARAMETER1,TYPE PARAMETER2….) { instruction1; instruction2; ….. return (whatever you want); }
The actual instructions for the function to execute. Needs to have variable names in definition – int FindSum(int X, int Y)
Function Call The function must be told to run Runs within body of main function FUNCTIONNAME(PARAM1,PARAM2);
3 Ways to Communicate Data 1.Return values 2.Use of parameters within functions 3.Global Variables
Use of Return Values Float FindDiff(float,float); Float FindDiff(float first, float second) { float differ; differ= first-second; return differ; }
Use of Return Values
Restrictions Using the return value method, we can only return one piece of data back from the functions.
Assign Make a program that inputs 2 numbers, and outputs the sum, difference, and product of the 2 numbers. Use at least 3 different functions.