Functions: Computer Programming1
Functions: Computer Programming1
Functions
A program can be thought of as consisting of subparts, such as obtaining the input data, calculating
the output data, and displaying the output data. These subparts are called functions.
top-down design would make the program easier to understand, easier to change if need be, and
as will become apparent, easier to write, test, and debug.
One of the advantages of using functions to divide a programming task into subtasks is that
different people can work on the different subtasks.
C++, like most programming languages, has facilities to include separate subparts inside of a
program. In other programming languages these subparts are called subprograms, procedures, or
methods, while in C++ these subparts are called functions.
e.g. for common mathematical calculations we include the file math with the following statement:
#include <math.h> //directive which contains the function prototypes for the
mathematical functions in the math library.
Mathematical functions
Math library functions allow the programmer to perform a number of common
mathematical calculations:
37
Computer Programming1 Academic Year 2018-2019
Function Description
sqrt(x) square root
sin(x) trigonometric sine of x (in radians)
trigonometric cosine of x (in
cos(x)
radians)
trigonometric tangent of x (in
tan(x)
radians)
exp(x) exponential function
log(x) natural logarithm of x (base e)
log10(x) logarithm of x to base 10
abs(x) absolute value (unsigned)
ceil(x) rounds x up to nearest integer
floor(x) rounds x down to nearest integer
pow(x,y) x raised to power y
Example 1: By using predefined function, Write program that find x values from the equation :
where:
( ) ( )
√
| | | |
38
Computer Programming1 Academic Year 2018-2019
Function definitions
There are two type of user-defined functions:
q First type: Return one value by its name function
Uses: use when we need a function that calculate and return just ONE value
[there are no input (cin) or output (cout) statements]
Define:
List of formal parameters names and their types
type of data that the Identifier of function that receive the values of the arguments
function returns name
Note: : The return _type of the function may be (int, float, char, etc.)
q Second type: Not return any value by its name (Void Function)
Uses: use when we need a function that calculate and return more than ONE value
or do subtask, we can here use input (cin) or output (cout) statements.
Define:
List of formal parameters names and their types
Identifier of function that receive the values of the arguments
name
39
Computer Programming1 Academic Year 2018-2019
Example : Following is the source code for a function called max(). This function takes two parameters num1
and num2 and returns the maximum between the two:
// function returning the max between two numbers
int max(int num1, int num2)
{
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Function Declarations
A function declaration tells the compiler about a function name and how to call the function. The actual body
of the function can be defined separately.
For the above defined function max(), following is the function declaration:
int max(int num1, int num2);
Notes :
q Parameter names are not important in function declaration only their type is required, so following is
also valid declaration:
int max(int, int);
q Function declaration is required when you define a function in one source file and you call that function
in another file or you define function after main function. In such case, you should declare the function
at the top of the file calling the function.
40
Computer Programming1 Academic Year 2018-2019
q There are two ways to write the declaration and definition of function depending on their place in
program
# include <iostream.h> # include <iostream.h>
//Function declaration ; // Function definition
void main() void main()
{ {
.... ....
// function call //function call
} }
//Function definition
Calling a Function
While creating a C++ function, you give a definition of what the function has to do. To use a function, you will
have to call or invoke that function.
طWhen a program calls a function, program control is transferred to the called function.
طA called function performs defined task and when its return statement is executed or when its function-
ending closing brace is reached, it returns program control back to the main program.
طTo call a function, you simply need to pass the required parameters along with function name, and if
function returns a value, then you can store returned value. For example:
41
Computer Programming1 Academic Year 2018-2019
After running the source code it would produce the following result:
Call by value This method copies the actual value of an argument into the formal
parameter of the function. In this case, changes made to the parameter
( IN-ONLY)
inside the function have no effect on the argument.
Call by reference This method copies the reference of an argument into the formal
parameter. Inside the function, the reference is used to access the actual
(IN-OUT) argument used in the call. This means that changes made to the
parameter affect the argument.
Note: By default, C++ uses call by value to pass arguments. In general, this means that code within a function
cannot change the arguments used to call the function .
طA function definition has a name, parentheses pair containing zero or more parameters and a
body.
طFor each parameter, there should be a corresponding declaration that occurs before the body.
Any parameter not declared is taken to be an integer by default.
42
Computer Programming1 Academic Year 2018-2019
Return Statement :
§ The keyword return is used to terminate function and return a value to its caller.
§ The return may also be used to exit a function without returning a value.
§ Its may or may not include on expression.
§ Its general syntax is:
return ;
return (exp);
The return statements terminate the exaction of the function and pass the control back to the calling
environment.
Call Examples :
§ Assignment statement : a = sum (n, m);
§ If statement : if (sum (n, m) >=4 )
§ Output statement: cout << sum (n, m);
طNot return by its name ( Void Function) : It uses when we need a function that calculate and
return more than one values or do special subtask
Parameters type:
1. call by value (IN-only ): copies the value of argument (actual parameter) into formal
parameter of the function. In this case, changes made to the parameter have no effect on
the arguments.
2. call by reference(INO-out): the address of an argument is copied into the parameter. Inside
the function, the address is used to access the actual argument used in the call. This means
that changes made to the parameter affect the argument.
43
Computer Programming1 Academic Year 2018-2019
Call :
§ We can write the function name with its arguments in any place can put a variable of
the same type.
Exercies:
1. Write C++ program that use function named powfun() that raises an integer number passed to it
to a positive integer power and returns the result as an integer.
2. Write C++ program can swap between two variables using function:
3. Write C++ program using a functions to read sequence of positive number, then print each
number with it factorial.
4. Write C++ program using a functions to read n of integer number, then print the summation and
average of even and odd numbers.
5. Write C++ program using function to calculate the average of two numbers entered by the user .
6. Write C++ program to calculate the squared value of a number passed from main program.
calculate the square of numbers from 1 to 10.
Functions Questions
1. Design the findMax() function accepts two double arguments (number1 and number2) and return
the max number.
2. Design a function named findAbs() that accepts a double number passed to it and returns that
number’s absolute value.
3. Design a function named mult() that accepts two floating-point numbers as parameters, multiplies
these two numbers, and returns the result.
4. Design a function named square() that computes and returns the square of the integer value passed
to it.
5. Design A function named powfun() that raises an integer number passed to it to a positive integer
power and returns the result as an integer.
6. Design a function named table() that produces a table of numbers from 1 to 10, their squares, and
their cubes.
44
Computer Programming1 Academic Year 2018-2019
7. Design a function named check() that accept two integer numbers as parameters, the function
return "ok" if the second number is factorial of first number otherwise the function return "not
ok"
8. Design a function to read sequence of number (N), then print the times repeat of a specific number.
9. Design a function to read sequence of number, then print each number with it factorial.
return 0;
}
45
Computer Programming1 Academic Year 2018-2019
When the above code is compiled and executed, it produces the following result:
Total value is :300
Total value is :120
46
Computer Programming1 Academic Year 2018-2019
47
Computer Programming1 Academic Year 2018-2019
48
Computer Programming1 Academic Year 2018-2019
Parameters Restrictions
49