Function
Function
SECTION 1
FUNCTION
1 Dr. Doaa Hany Elsayed
[email protected]
FUNCTION
Concept: A program may be broken up into manageable
functions.
2
STRUCTURE OF FUNCTION
A function is a collection of statements that performs a specific
task.
A general form of a function looks like this :
3
STRUCTURE OF FUNCTION
4
FUNCTION WITHOUT PARAMETERS AND
WITHOUT RETURN VALUE
Example:
o Function calling:
o Output:
5
FUNCTION WITH PARAMETERS AND
WITHOUT RETURN VALUE
Example:
Function calling:
Output
6
FUNCTION WITHOUT PARAMETERS AND
WITH RETURN VALUE
Example:
Function calling:
Output
7
FUNCTION WITH PARAMETERS AND WITH
RETURN VALUE
Example:
Function calling:
Output
8
EXAMPLE 1
1. Write a program that consists of:
• A function Cal_Avg that receives 2 numbers and returns their Average
• Main function that reads the 2 numbers from the user, calls Cal_Avg and
displays the average
• Answer:
9
CALL BY VALUE
When a function with multiple parameters is called, the arguments
are passed to the parameters in order.
12
CALL BY REFERENCE
value refVar
For example:
8
4
output
13
EXERCISE
Show the output:
A.
Answer:
14
4 11 16
1 5 7
EXERCISE
Show the output:
B.
Answer:
15
4 11 16
4 11 16
ASSIGNMENT
1. Write a program that consists of:
• Function calc_NetSalary that Receives the worked
hours and pay rate and return the calculated net
salary :
o GrossSalary= WorkedHours* PayRate;
o NetSalary=GrossSalary-10;
• main function a
• Read from user hours and rate