What is a function? It is a self-contained program segment that carries out some specific, well-defined task when called. There are two types of functions. They are:
1) Library or built-in functions: These functions are pre-defined. Users can only use these functions but cannot modify them. Users may not understand the internal working of these functions. It is enough if we know how to use them.
2) User-defined functions: Functions defined by the user according to their requirement. The user can modify these functions. Main function is also a user-defined function but the function name, number of arguments and argument types are defined by the language, although the statements inside it are specified by the user.
Ex: square(), cube() etc can be written as user-defined functions.
Advantages of using functions:
- Avoids repetition of the code.
- Increases reusability i.e., existing code can be used rather than trying to develop new code. Also, the function can be used by many other programs.
- The length of the source code (ie., the program size) is reduced.
- Easy to debug.
- Increases readability.
- Program development time, effort and cost can be reduced.
To write programs using functions, we must know about the following three:
a) Function definition: It as two parts namely function header and function body.
[ReturnType] FunctionName([type argl ,type arg2, , type argN])
[ local declarations; ]
[ return (expression); ]
b) Function call: This statement should appear in the calling function. It is given by writing the function name followed by an optional list of parametersenclosed within parenthesis and finally terminated by a ';' semicolon. In function call, the data type of the parameters is not needed.
functionName(argl, arg2, ................argn); //function which does not return any value.
X = functionName(argl, arg2,...............argn); //function which returns a value.
c) Function Prototype or declaration: If main() calls user-defined functions which returns other than an integer value, those called functions should be defined before main(). Or, if these user-defined functions have to be defined after main(), then those functions should be declared before calling them. This function declaration is called function prototype.
float f1 ;