4 - Functions - Part2
4 - Functions - Part2
UNIVERSITY
College of Computer Science & IT
Department of CS
Welcome to
CS 221:Fundamentals of Programming
Weeks (4): Functions – Part 2
Chapters 9 and 10 (Zak Textbook)
Chapter 4 (Savitch Textbook)
Objectives
2
CS221: Fundamentals of Programming
USER\PROGRAMMER-DEFINED
FUNCTIONS
3
What is user-defined functions
4
Programmer-Defined Functions
• Two components of a function definition
– Function declaration (or function prototype)
• Shows how the function is called توضح كيف راح ننادي الفنكشن يعني اسمها
• Must appear in the code before the function can be called
• Syntax: الزم يكون موجود البروتوتايب قبل ال ننادي الفنكشن ونستخدمها
Type_returned Function_Name(Parameter_List);
To tell the compiler that we have a function
– Function definition توضح ايش مهمة الفنكشن وايش الكود اللي داخلها
;
• Describes how the function does its task
• Can appear before or after the function is called
• Syntax: عادي يكون قبل او بعد ما ننادي الفنكشن مايهم
Type_returned Function_Name(Parameter_List)
{
//code to make the function work
}
5
Function Declaration
6
Function Definition Syntax
7
Function Definition
8
Function Prototypes
• When a function definition appears below the main
function, you must enter a function prototype above the
main function
• A function prototype is a statement that specifies the
function’s name, data type of its return value, and data
type of each of its formal parameters (if any)
– Names for the formal parameters are not required
• Programmers usually place function prototypes at
beginning of program, after the #include directives
عادي نخلي الفورمال باراميتر بدون اسم بس الزم نكتب النوع حقهم
9
Calling a Function
• Like Pre-defined functions, A user-defined function
must be called (invoked) to perform its task
• main is automatically called when program is run
• Other functions must be called by a statement
• Syntax for calling a function: x and y entered by the user
Summation (1,10);
functionName([argumentList]); Summation (x,y);
Summation (x,x+10);
– argumentList is list of actual arguments (if any)
– An actual argument can be a variable, named constant, literal
constant, or keyword.
• Number, data type, and ordering of actual arguments must
match the formal parameters in function header
10
Calling a Function (cont’d.)
• Value-returning functions are typically called from
statements that:
– Assign the return value to a variable
– Use the return value in a calculation or comparison
– Display the return value
X=summation (1,10);
X= 3*summation (1,10);
cout<<summation (1,10);
11
Calling a Function (cont’d.)
• C++ allows you to pass either a variable’s value or its
address to a function
– Passing a variable’s value is referred to as passing by
value
– Passing a variable’s address is referred to as passing by
reference
12
Flow of Execution
• Execution always begins at the first statement in the function
main
• Other functions are executed only when they are called
• Function prototypes appear before any function definition
– The compiler translates these first
• The compiler can then correctly translate a function call
13
)Flow of Execution (continued
• A function call results in transfer of control to the first
statement in the body of the called function
ملا انادي الفنكشن بيترك ال calllerاللي هو املني او الفنكشن اللي ناديتها فيه وبيروح على طول الول ستيتمنت في الفنكشن
اللي ناديتها
• After the last statement of a function is executed, control is
passed back to the point immediately following the
بعد ما ينفذ الفنكشن بيرجع على طول الول ستيتمنت في ال callerبعد ال callيعني اللي function call
بتكون بعد ما ناديت الفنكشن يعني بيرجع يكمل بعد املكان اللي وقف فيه
14
Flow of Execution (continued)
-- i is now
5
void main() int max(int num1, int num2}
{ {
int i = 5; int result;
int j = 2;
if (num1 > num2)
int k = max( i, j );
result = num1;
else
cout << “The maximum between “ << i << result = num2;
“and “ << j << “ is “ << k;
return result;
}
}
15
Flow of Execution (continued)
-- j is now
2
void main() int max(int num1, int num2}
{ {
int i = 5; int result;
int j = 2;
if (num1 > num2)
int k = max( i, j );
result = num1;
else
cout << “The maximum between “ << i << result = num2;
“and “ << j << “ is “ << k;
return result;
}
}
16
Flow of Execution (continued)
-- call max(5, 2)
17
Flow of Execution (continued)
call max(5, 2)
-- Pass the value of 5 to
num1
void main() Pass the value of 2 to
int max(int num1, int num2}
{ num2
{
int i = 5; int result;
int j = 2;
if (num1 > num2)
int k = max( i, j );
result = num1;
else
cout << “The maximum between “ << i << result = num2;
“and “ << j << “ is “ << k;
return result;
}
}
18
Flow of Execution (continued)
-- declare variable
result 5 2
void main() int max(int num1, int num2}
{ {
int i = 5; int result;
int j = 2;
if (num1 > num2)
int k = max( i, j );
result = num1;
else
cout << “The maximum between “ << i << result = num2;
“and “ << j << “ is “ << k;
return result;
}
}
19
Flow of Execution (continued)
-- (num1 > num2) is true
since
num1 is 5 and num2 5 2
is 2
void main() int max(int num1, int num2}
{ {
int i = 5; int result;
int j = 2;
if (num1 > num2)
int k = max( i, j );
result = num1;
else
cout << “The maximum between “ << i << result = num2;
“and “ << j << “ is “ << k;
return result;
}
}
20
Flow of Execution (continued)
-- result is
now 5 5 2
void main() int max(int num1, int num2}
{ {
int i = 5; int result;
int j = 2;
if (num1 > num2)
int k = max( i, j );
result = num1;
else
cout << “The maximum between “ << i << result = num2;
“and “ << j << “ is “ << k;
return result;
}
}
21
Flow of Execution (continued)
--
5 2
void main() int max(int num1, int num2}
{ {
int i = 5; int result;
int j = 2;
if (num1 > num2)
int k = max( i, j );
result = num1;
else
cout << “The maximum between “ << i << result = num2;
“and “ << j << “ is “ << k;
return result;
}
}
22
Flow of Execution (continued)
return max(5, 2) and
assign the return
-- value to k
23
Flow of Execution (continued)
Execute the
-- cout
statement
24
Programmer-Defined Functions
(Example)
25
Programmer-Defined Functions
(Example)
26
Why is this program not doing anything?
27
void-Functions
28
void-Function Definition
• Two main differences between void-function
definitions and the definitions of functions
that return one value
– Keyword void replaces the type of the value returned type تنكتب بدال الvoid يعني
• void means that no value is returned by the function
– The return statement does not include and expression
بس اذاreturn افضل اني ما اكتب
• Example:
;return بكتبها تكون بدون شي
29
Using a void-Function
30
void-Function Calls
31
void-Functions
Why Use a Return?
• Is a return-statement ever needed in a
void-function since no value is returned?
– Yes!
• What if a branch of an if-else statement requires
that the function ends to avoid producing more
output, or creating a mathematical error?
• void-function in Display 5.3, avoids division by zero
with a return statement
اذا كان عندنا شروط في الفنكشنvoid في الreturn بنحتاج نستخدم
اذا تحققbreak مثلreturn ومانبيه يكمل اذا تحقق الشرط فبتصير ال
الشرط تطلع من الفنكشن
32
Display 5.3
33
Creating Program-Defined Void
Functions
37
لو عكست بينهم بيصير logic error
38
Alternate Declarations
39
Order of Arguments
• Compiler checks that the types of the arguments
are correct and in the correct sequence.
• Compiler cannot check that arguments are in the
correct logical order مايقدر يتأكد اني حاطتهم بالترتيب الصح
• Example: Given the function declaration:
char grade(int received_par, int minScore_par);
40
41
Min score هنا هناscore بتجي ال
42
Function Definition Syntax
43
bool Return Values
44
Function appropriate
45
User-defined Function Conclusion
• Can you
– Write a function declaration and a function definition
for a function that takes three arguments, all of type
int, and that returns the sum of its three arguments?
– Describe the call-by-value parameter mechanism?
– Write a function declaration and a function definition
for a function that takes one argument of type int
and one argument of type double, and that returns a
value of type double that is the average of the two
arguments?
46
Exercise
• Write the C++ code for a function that receives an
integer passed to it. The function should divide the
integer by 2 and then return the result, which may
contain a decimal place. Name the function
divideByTwo. Name the formal parameter
wholeNumber.
48
Passing Variables by Reference
Reference — Adress
49
Passing Variables by Reference
(cont’d.)
• If receiving function appears below main, you must also
include the & in the receiving function’s prototype
• You enter the & immediately before the name of the formal
parameter in the prototype
– If the prototype does not contain the formal parameter’s
name, you enter a space followed by & after the formal
parameter’s data type
51
Passing Variables by Reference
(cont’d.)
Passing by
reference
SCOPE OF VARIABLES
60
The Scope and Lifetime of a Variable
• A variable’s scope indicates where in the program the
variable can be used
61
The Scope and Lifetime of a Variable
(cont’d.)
• Local variables can be used only by the function in which
they are declared or in whose parameterList they appear
– The scope of a local variable starts from its declaration and continues
to the end of the block that contains the variable. A local variable
must be declared before it can be used
– You can declare a local variable with the same name multiple times in
different non-nesting blocks in a function, but avoid declaring local
variables twice in nested blocks x in function 1 different from x in function 2
– If two methods each have a local variable of the same name, they are still two
entirely different variables
62
The Scope and Lifetime of a Variable
(cont’d.)
A variable declared in the initial action part of a for loop header has
its scope in the entire loop. But a variable declared inside a for loop
body has its scope limited in the loop body from its declaration and
to the end of the block that contains the variable
void method1() {
.
.
for (int i = 1; i < 10; i++) {
.
The scope of i .
int j;
.
The scope of j .
.
}
63
The Scope and Lifetime of a Variable
(cont’d.)
It is OK to declare i in two Avoid declaring same variable name
non-nested blocks in nested blocks.
Note the different i variables with
void method1() { different scopes
int x = 1; void method2() {
int y = 1;
int i = 1;
for (int i = 1; i < 10; i++) { int sum = 0;
x += i;
} for (int i = 1; i < 10; i++)
sum += i;
for (int i = 1; i < 10; i++) { }
y += i;
} }
}
65
The Scope and Lifetime of a Variable
(cont’d.)
• Declaring a variable as global can allow unintentional errors
to occur
– e.g., a function that should not have access to the variable
inadvertently changes the variable’s contents
افضل ما نستخدمه الن ممكن يسبب اخطاء غير مقصودة
• You should avoid using global variables unless necessary
66
Example: global
#include <iostream>
using namespace std;
// Global variable declaration:
int g;
int main () {
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
Output: 30
67
Example: same name for local and global
variables
#include <iostream>
using namespace std;
// Global variable declaration:
int g = 20;
int main () {
// Local variable declaration:
int g = 10;
cout << g;
return 0; Any change in main function will affect the global
}
Output: 10
68
Exercise
• Write the C++ code for a function that receives four double
numbers.
– The function should calculate the average of the four numbers
and then return the result. Name the function calcAverage.
– Name the formal parameters num1, num2, num3, and num4.
– Also write an appropriate function prototype for the
calcAverage function.
– In addition, write a statement that invokes the calcAverage
function and assigns its return value to a double variable named
quotient.
– Use the following numbers as the actual arguments: 45.67,
8.35, 125.78, and 99.56.
69
Exercise
• Body
double calcAverage(double num1, double num2, double num3,
double num4)
{
return (num1 + num2 + num3 + num4) / 4;
} //end of calcAverage function
• Prototype
double calcAverage(double num1, double num2, double num3,
double num4);
OR: double calcAverage(double, double, double, double);
• Assigning Value
quotient = calcAverage(45.67, 8.35, 125.78, 99.56);
70
Exercise
• Write the C++ code for a void function that receives three
double variables
– the first two by value and the last one by reference.
– Name the formal parameters n1, n2, and answer.
– The function should divide the n1 variable by the n2
variable and then store the result in the answer variable.
Name the function calcQuotient.
– Also write an appropriate function prototype for the
calcQuotient function.
استدعاء
– In addition, write a statement that invokes the
calcQuotient function, passing it the num1, num2, and
quotient variables.
71
Exercise
void calcQuotient(double n1, double n2, double
&answer)
{
answer = n1 / n2;
} //end of calcQuotient function
Prototype
void calcQuotient(double, double, double &); OR:
void calcQuotient(double n1, double n2, double
&answer);
Calling
calcQuotient(num1, num2, quotient);
72
Any Questions
73