0% found this document useful (0 votes)
17 views

4 - Functions - Part2

1) This document discusses user-defined functions in C++, including how to create, declare, define, call, and pass arguments to functions. 2) It explains that a function declaration specifies the function's name, return type, parameters, and formal parameters while a function definition contains the function body and code. 3) The flow of execution begins in the main function and transfers to called functions, returning to the statement following the function call once execution completes.

Uploaded by

mareomah1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

4 - Functions - Part2

1) This document discusses user-defined functions in C++, including how to create, declare, define, call, and pass arguments to functions. 2) It explains that a function declaration specifies the function's name, return type, parameters, and formal parameters while a function definition contains the function body and code. 3) The flow of execution begins in the main function and transfers to called functions, returning to the statement following the function call once execution completes.

Uploaded by

mareomah1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

IMAM ABDULRAHMAN BIN FAISAL

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

• Introduce user\programmer-defined functions and discover


how to create them in a program.
• Passing by reference and passing by value
• Variables scope: Local and global

2
CS221: Fundamentals of Programming

USER\PROGRAMMER-DEFINED
FUNCTIONS
3
What is user-defined functions

• A user-defined function (UDF) is


a function provided by the user of a program or
environment, in a context where the usual
assumption is that functions are built into the
program or environment.

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

• Tells the return type


• Tells the name of the function
• Tells how many arguments are needed
• Tells the types of the arguments
• Tells the formal parameter names
– Formal parameters are like placeholders for the actual
arguments used when the function is called
– Formal parameter names can be any valid identifier
• Example:
double totalCost(int numberPar, double pricePar);
// Compute total cost including 15% sales tax on
// numberPar items at cost of pricePar each

6
Function Definition Syntax

7
Function Definition

• Function body contains instructions for performing the


function’s assigned task
• Surrounded by braces à { }
• Last statement is usually the return statement
– Returns one value (must match return data type in
function header)
• After return statement is processed, program execution
continues in calling function

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

‫ بذي الطريقة‬local ‫ بدال‬global ‫ يصيرون‬formal parameters ‫نقدر نخلي ال‬

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‬‬
‫بتكون بعد ما ناديت الفنكشن يعني بيرجع يكمل بعد املكان اللي وقف فيه‬

‫‪• A value-returning function returns a value the returned‬‬


‫‪value replaces the function call statement‬‬
‫الفنكشن بترجع لي قيمة والقيمة‬
‫يعني مثال الفنكشن رجعت لي ‪ ٥٥‬وانا ناديتها في‬
‫هاذي بتنحط مكان اللي ناديت‬
‫مكان ثاني بتجي القيمة مكان اللي ناديتها فيه‬
‫فيه الفنكشن‬

‫‪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)

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;
}
}

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;
}
}

return result, which


is 5

22
Flow of Execution (continued)
return max(5, 2) and
assign the return
-- value to k

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;
}
}

23
Flow of Execution (continued)
Execute the
-- cout
statement

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;
}
}

24
Programmer-Defined Functions
(Example)

25
Programmer-Defined Functions
(Example)

26
Why is this program not doing anything?

27
void-Functions

• In top-down design, a subtask might produce


– No value (just input or output for example) void-function
– One value
– More than one value (using pointers)
• We have seen how to implement functions that
return one value
• A void-function implements a subtask that
returns no value or more than one value

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 ‫بكتبها تكون بدون شي‬

void showResults(double f_degrees, double c_degrees)


{

cout << f_degrees


<<“ degrees Fahrenheit is euivalent to” << endl
<< c_degrees << “ degrees Celsius.” << endl;
return;
}

29
Using a void-Function

• void-function calls are executable statements


– They cannot be part of another statement Stand alone statement

– They end with a semi-colon


• Example:
showResults(32.5, 0.3);

NOT: cout << showResults(32.5, 0.3);

cout ‫مايصير اطبعها ب‬


!!!‫ممنوعععع‬

30
void-Function Calls

• Mechanism is nearly the same as the function


calls we have seen ‫ﻧﻌﻮض اﻻﻛﺸﻞ ﺑﺎراﻣﯿﺘﺮ ﻓﻲ اﻟﻔﻮرﻣﺎل‬
– Argument values are substituted for the formal
parameters
• It is common to have no parameters in void-functions
– In this case there will be no arguments in the function call
– Statements in function body are executed
– Optional return statement ends the function
• Return statement does not include a value to return
• Return statement is implicit if it is not included
‫ افتراضيه مايحتاج احطها‬return ‫يعني الريتيرن مضمنة فيها والبروقرام بيفهم تلقائي ان الفنكشن انتهت بتكون عنده‬

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

Figure 10-5 ABC Company program


34
Creating Program-Defined Void
Functions (cont’d.)

Figure 10-5 ABC Company program (cont’d.)


35
36
Function Call Details

• The values of the arguments are plugged into


the formal parameters (Call-by-value mechanism
with call-by-value parameters)
– The first argument is used for the first formal
parameter, the second argument for the second
formal parameter, and so forth.
– The value plugged into the formal parameter is
used in all instances of the formal parameter in the
function body
‫بس قاعد يقول انه يمشي بالترتيب يعوض اول‬
‫باراميتر في اول باراميتر في الفنكشن‬

37
‫لو عكست بينهم بيصير ‪logic error‬‬

‫‪38‬‬
Alternate Declarations

• Two forms for function declarations (prototypes).


– List formal parameter names
– List types of formal parmeters, but not names
• Examples: ‫ﻓﻲ اﻟﺒﺮوﺗﻮﺗﺎﯾﺐ اﻧﺎ اﺧﺘﺎر اذا اذﻛﺮ اﺳﻢ اﻟﺒﺎراﻣﯿﺘﺮ او ﻻ‬
double totalCost(int numberPar, double pricePar);
All right in prototype
double totalCost(int, double);
• First aids description of the function in comments
• Function headers must always list formal
parameter names! ‫ﻓﻲ اﻟﮭﯿﺪر اﻟﻠﻲ ﺗﺤﺘﮫ ﺑﻜﺘﺐ اﻟﻔﻨﻜﺸﻦ اﻣﺒﻠﻤﻨﺘﯿﺸﻦ‬
‫ﻻزم اﻛﺘﺐ اﻻﺳﻢ ﺿﺮوري‬

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);

int received = 95, minScore = 60;

cout << grade( minScore, received);


– Produces a faulty result because the arguments are not in
the correct logical order. The compiler will not catch this!

40
41
Min score ‫هنا‬ ‫ هنا‬score ‫بتجي ال‬

42
Function Definition Syntax

• Within a function definition


– Variables must be declared before they are used
– Variables are typically declared before the
executable statements begin
– At least one return statement must end the
function
• Each branch of an if-else statement might have its
own return statement

43
bool Return Values

• A function can return a bool value


– Such a function can be used where a boolean
expression is expected
• Makes programs easier to read
• if (((rate >=10) && ( rate < 20)) || (rate == 0))
is easier to read as
if (appropriate (rate))
– If function appropriate returns a bool value based
on the expression above

44
Function appropriate

• To use function appropriate in the if-statement


if (appropriate (rate))
{ … }

appropriate could be defined as


bool appropriate(int rate)
{
return(((rate >=10) && ( rate < 20)) || (rate == 0));
}

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.

double divideByTwo(int wholeNumber)


{
return wholeNumber / 2.0;
}
47
‫‪CS221: Fundamentals of Programming‬‬

‫كأني اسوي شير لشغلي بالدروب بوكس واعطيه صديقتي وهي‬


‫تعدل عليه فراح يتأثر‬

‫‪PASSING BY REFERENCE‬‬ ‫يتأثر‬

‫‪PASSING BY VALUES‬‬ ‫ما يتأثر‬


‫كآني أعطي صديقتي نسخة ورقية من شغلي وهي‬
‫تعدل عليها ما راح يتأثر شغلي‬

‫‪48‬‬
Passing Variables by Reference
Reference — Adress

• Passing a variable’s address in internal memory to a


function is referred to as passing by reference
• You pass by reference when you want the receiving
function to change the contents of the variable

• To pass by reference in C++, you include an ampersand


(&) before the name of the formal parameter in the
receiving function’s header
• Ampersand (&) is the address-of operator
– Tells the computer to pass the variable’s address rather
than a copy of its contents

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

• Void functions use variables passed by reference to send


information back to the calling function, instead of a return
value
50
Passing Variables by Reference
(cont’d.)

If we use passing by value the value of a will


not affect when we return to the main

But because we use passing by reference the value


of a affected

51
Passing Variables by Reference
(cont’d.)

Passing by
reference

Any change in function will


affect the original variable

Figure 10-13 Modified age message program 52


53
54
55
56
57
58
59
CS221: Fundamentals of Programming

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

• A variable’s lifetime indicates how long the variable remains


in the computer’s internal memory

• Both scope and lifetime are determined by where you


declare the variable in the program
– Variables declared within a function and those that appear in a
function’s parameterList have a local scope and are referred to
as local variables

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

– Remain in internal memory until the function ends

– 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;
} }
}

It is WRONG to redefine y. There is different x variables with different scopes


void incorrectMethod(int x, int y) {
int y = 1, sum = 0;

for (int x = 1; x < 10; x++) {


sum += x;
}
64
}
The Scope and Lifetime of a Variable
(cont’d.)
include ‫نحطها برا كل الدوال يعني تحت‬

• Global variables are declared outside of any function in the


program
– Remain in memory until the program ends

• Any statement can use a global variable


– Example: Swap function

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

• If more than one function needs to access the same variable,


it is better to create a local variable in one function and pass
it to other functions that need it

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

• Thanks for Listening J

73

You might also like