Lab Task #7 Functions
Lab Task #7 Functions
Lab 7
Functions
1. Library Function
2. User-defined Function
Library Function
Programmer can use library function by invoking function directly; they don't need to
write it themselves.
Program 1
The function definition of sqrt()(body of that function) is present in the cmath header
file.
You can use all functions defined in cmath when you include the content of file cmath in
this program using #include <cmath> .
Every valid C++ program has at least one function, that is, main()function.
User-defined Function
C++ allows programmer to define their own function. A user-defined function groups code to
perform a specific task and that group of code is given a name (identifier). When the function is
invoked from any part of program, it all executes the codes defined in the body of function.
Lab Task #7 Functions
Program 2
Output:
In C++, function prototype is a declaration of function without its body to give compiler
information about user-defined function. Function prototype in the above example is:
You can see that, there is no body of function in prototype. Also, there are only return
type of arguments but no arguments. You can also declare function prototype as below
but it's not necessary to write arguments.
Function Call
To execute the codes of function body, the user-defined function needs to be
invoked(called).
Function Definition
The function itself is referred as function definition. Function definition in the above
program is:
// Function definition
int add;
add = a + b;
Lab Task #7 Functions
return add;
When the function is called, control is transferred to the first statement of the function
body.
When all codes inside function definition is executed, control of program moves to the
calling program.
Return Statement
A function can return a single value to the calling program using return statement.
In the above program, the value of add is returned from user-defined function to the
calling program using statement below:
return add;
Lab Task #7 Functions
Program 3
Output:
Program 4
Output
Date: __________________
Marks Obtained: ____________________
Instructor’s Signature: _________________