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

5 - Functions - Part3

The document discusses array parameters in functions. Arrays can be passed to functions by passing the base address. Functions can process arrays of different sizes if they include a parameter for the array size. The const modifier can be used to prevent a function from modifying array elements.

Uploaded by

mareomah1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

5 - Functions - Part3

The document discusses array parameters in functions. Arrays can be passed to functions by passing the base address. Functions can process arrays of different sizes if they include a parameter for the array size. The const modifier can be used to prevent a function from modifying array elements.

Uploaded by

mareomah1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

IMAM ABDULRAHMAN BIN FAISAL

UNIVERSITY
College of Computer Science & IT
Department of CS

Welcome to
CS 221:Fundamentals of Programming
Weeks (5): Functions – Part 3
Chapters 9 and 10 (Zak Textbook)
Chapter 4,5 (Savitch Textbook)
Outline

• Array in functions
• Functions overloading
• Recursion

2
CS221: Fundamentals of Programming

ARRAY IN FUNCTIONS

3
Arrays in Functions

• Indexed variables can be arguments to functions


– Example: If a program contains these declarations:
int i, n, a[10];
void my_function(int n);

– Variables a[0] through a[9] are of type int, making these


calls legal:
my_function(a[0]);
my_function(a[3]);
my_function(a[i]);

4
Passing array
elements

5
Arrays as Function Arguments
the entire array ‫ او نرسل‬element by element ‫ممكن نستخدم االراي بالفنكشن باننا نرسلها‬

• A formal parameter can be for an entire array


– Such a parameter is called an array parameter
• It is not a call-by-value parameter If the value changed inside the function it will not affect
the original value

• It is not a call-by-reference parameter any change inside the function it will affect
the original value

• Array parameters behave much like call-by-reference


parameters

6
Base Address of an Array and Array in
Computer Memory
• The base address of an array is the address, or memory location
of the first array component
• If list is a one-dimensional array, its base address is the
address of list[0]
• When we pass an array as a parameter, the base address of the
actual array is passed to the formal parameter
‫اتوقع اول عنصر باالراي اللي يعتبر العنوان حقها يروح للفورمال باراميتر‬

Base address is address or memory location to

( first array element )

7
Base Address of an Array and Array in
Computer Memory

‫يعني من اول‬
element
‫بيعرف ال‬
location
Array Parameter Declaration

• An array parameter is indicated using empty


brackets in the parameter list such as

void fill_up(int a[ ],int size);

‫ﻟﻤﺎ ﻧﻌﺮف ﻓﻨﻜﺸﻦ وﻧﺮﺳﻞ ﻟﮭﺎ اراي ﻧﺤﻂ اﻗﻮاس وﺗﻜﻮن ﺗﺴﺘﻘﺒﻞ اﻟﺴﺎﯾﺰ ﺑﻌﺪ‬

9
Function Calls With Arrays

• If function fill_up is declared in this way:


void fill_up(int a[ ], int size);
‫هنا انا حطيت اسم من عندي لالراي والسايز للفورمال باراميتر‬

• and array score is declared this way:


int score[5], number_of_scores;

• fill_up is called in this way:


fill_up(score, number_of_scores);
‫اسم االراي‬
‫السايز‬

‫ﻟﻤﺎ ﻧﻨﺎدي اﻟﻔﻨﻜﺸﻦ ﻧﺮﺳﻞ ﻟﮭﺎ اﻻﻛﺸﻞ ﺑﺎراﻣﯿﺘﺮ ﻟﻼراي اﺳﻤﮭﺎ ﺑﺲ ﺑﺪون اﻗﻮاس وﻧﺮﺳﻞ اﻟﺴﺎﯾﺰ ﺑﻌﺪ ﻛﺮﻗﻢ‬

10
Example: Function Calls With Arrays

11
Function Call Details

• A formal parameter is identified as an array


parameter by the [ ]'s with no index expression

void fill_up(int a[],int size);


In call
• An array argument does not use the [ ]'s

fill_up(score, number_of_scores);
‫اﺳﻢ ﺑﺲ‬
[] ‫في الفورمال باراميتر نحط‬

‫بس في االكشل باراميتر نحط اسم االراي بس‬

12
Array Formal Parameters

• An array formal parameter is a placeholder for


the argument
– When an array is an argument in a function call, an action
performed on the array parameter is performed on the
array argument
‫اي تغيير في الفنكشن راح يغير في االراي االصلية الن االراي تتصرف كانها باي رفرنس‬

– The values of the indexed variables can be changed by


the function
‫قيم املتغيرات في االراي ممكن تتغير بواسطة الفنكشن‬

13
Array Argument Details

• What does the computer know about an array?


– The base type int double string
– The address of the first indexed variable
– The number of indexed variables ‫طﻮل اﻻراي او ﻋﺪد اﻟﻔﺎرﯾﺒﻞ‬
• What does a function know about an array
argument?
– The base type ‫ﻧﻮع اﻻراي‬
– The address of the first indexed variable ‫اﻻدرس ﺣﻖ اول اﻟﻤﻨﺖ‬

“The function doesn’t know the size of the array, so we have to


send it ”

14
Array Parameter Considerations

• Because a function does not know the size of


an array argument…
– The programmer should include a formal parameter that
specifies the size of the array
– The function can process arrays of various sizes
• Function fill_up from previous example can be used to
fill an array of any size:

fill_up(score, 5);
fill_up(time, 10); ‫ﯾﻌﻨﻲ ﻧﻔﺲ اﻟﻔﻨﻜﺸﻦ اﻗﺪر‬
‫ ارراي ﻣﺨﺘﻠﻔﯿﻦ‬٢ ‫ارﺳﻞ ﻟﮭﺎ‬
‫ﻛﻞ وﺣﺪة طﻮﻟﮭﺎ ﻣﺨﺘﻠﻒ‬

15
A Complete Example
#include <iostream> double getAverage(int arr[], int
Using namespace std; size) {
int i;
double getAverage(int arr[], int double avg = 0.0;
size); double sum = 0.0 ;
for (i = 0; i < size; ++i)
int main () { {
/* an int array with 5 elements */ sum += arr[i];
}
int balance[5] = {1000, 2, 3, 17, avg = sum / size;
50}; return avg;
double avg;
}
/* pass pointer to the array as an
argument */

avg = getAverage( balance, 5 ) ;


/* output the returned value */
cout<< "Average value is:“ << avg ;
return 0;
}
const Modifier

• Array parameters allow a function to change the


values stored in the array argument
• If a function should not change the values of the
array argument, use the modifier const
• An array parameter modified with const is a
constant array parameter
– Example:
void show_the_world(const int a[], int size);
‫يعني الحني االراي هي باي رفرنس فاي تغيير في الفنكشن بيغير‬
‫في االراي بس اذا ابي الفنكشن ماتغير في قيم االراي وتعدل‬
‫ قبل التايب واسم االراي‬const ‫عليها احط‬

17
Using const With Arrays

• If const is used to modify an array parameter:

– const is used in both the function


declaration(prototype) and definition to modify the array
parameter

– The compiler will issue an error if you write code that


changes the values stored in the array parameter
If we write const we cannot change the values

‫ وﺑﻌﺪﯾﻦ ﻋﺪﻟﺖ ﻋﻠﻰ اﻟﻘﯿﻢ ﻓﻲ اﻟﻔﻨﻜﺸﻦ ﺑﯿﺼﯿﺮ اﯾﺮور‬const ‫ﯾﻌﻨﻲ اذا ﺣﻄﯿﺖ‬

18
‫‪19‬‬

‫‪Using const With Arrays‬‬

‫هنا غيرت كل قيم االراي لصفر الني استخدمتها كارراي عادي‬

‫‪If there’s const, you cannot‬‬


‫‪change array elements‬‬

‫هنا ما اقدر اغير القيم بس اقدر استخدمها نفس ماهي واطبعها‬


‫‪19‬‬
Function Calls and const

• If a function with a constant array parameter


calls another function using the const array
parameter as an argument…

– The called function must use a constant


array parameter as a placeholder for the array

– The compiler will issue an error if a function is


called that does not have a const array parameter to
accept the array argument

20
const Parameters Example

• double compute_average(int a[ ], int size);

void show_difference(const int a[ ], int size)


{
double average = compute_average(a, size);
… ‫ عشان تقدر اﻟﻔﻨﻜﺸﻦ ﺣﻘﺘﻲ ﺗﺴﺘﺨﺪم ﻛﻮﻧﺴﺖ ﯾﻌﻨﻲ ﻣﻔﺮوض ﻣﺎﺗﻐﯿﺮ ﻗﯿﻢ‬const ‫الزم يكونون كلهم‬
‫اﻻراي ﺑﺲ اﻧﮭﺎ‬
} const ‫ﻣﺴﻮﯾﮫ ﻛﻮل ﻟﻔﻨﻜﺸﻦ ﺛﺎﻧﯿﮫ ﺗﻐﯿﺮ اﻟﻘﯿﻢ ﻓﻜﺬا ﻣﺎﯾﺼﯿﺮ ﻻزم ﯾﻜﻮﻧﻮن ﻛﻠﮭﻢ‬ ‫تناديها وال بيصير فيه خطأ‬

• compute_average has no constant array parameter


• This code generates an error message because
compute_average could change the array parameter

21
Returning An Array

• Recall that functions can return a value of


type int, double, char, …, or a class type

• Functions cannot return arrays

• We will learn later how to return a pointer to an array

22
Array in Functions Conclusion

• Can you

– Write a function definition for a function called


one_more, which has a formal parameter for an array
of integers and increases the value of each array element
by one.
– Are other formal parameters needed?

void one_more( int a[], int size);


void one_more(int a[ ], int size)
void one_more ( int array [ ], int size ) { //Precondition: size is the declared size of the array a.
for (int i=0; i<size; i++ ) //a[0] through a[size - 1] has been given values.
array[i] = array [i] +1; //Postcondition: a[index] has been increased by 1 for all indexed variables of a.
} {
for (int index = 0; index < size; index++)
a[index] = a[index] + 1;
}
23
CS221: Fundamentals of Programming

FUNCTION OVERLOADING

24
Overloading Function Names

• C++ allows more than one definition for the


same function name
– Very convenient for situations in which the “same”
function is needed for different numbers or types
of arguments
• Overloading a function name means providing
more than one declaration and definition using
the same function name

25
Overloading Examples
• double ave(double n1, double n2)
{
return ((n1 + n2) / 2);
}
• double ave(double n1, double n2, double n3)
{
return (( n1 + n2 + n3) / 3);
}
– Compiler checks the number and types of arguments
in the function call to decide which function to use

cout << ave( 10, 20, 30);

uses the second definition

‫اﻟﻜﻮﻣﺒﺎﯾﻠﺮ ﺑﯿﺨﺘﺎر اﻟﻔﻨﻜﺸﻦ ﺣﺴﺐ اﻻرﻗﯿﻮﻣﻨﺖ‬


‫اﻟﻠﻲ اﺣﻄﮭﺎ‬

26
Overloading Details

• Overloaded functions ‫ﻋﺪد ﻣﺨﺘﻠﻒ ﻣﻦ اﻟﻔﻮرﻣﺎل ﺑﺎراﻣﯿﺘﺮ‬

– Must have different numbers of formal


parameters
AND / OR ‫اﻟﺘﺎﯾﺐ ﺣﻖ اﻟﺒﺎراﻣﯿﺘﺮ ﻣﺨﺘﻠﻒ‬

– Must have at least one different type of


parameter ‫املهم اذا كانوا نفس‬
‫االسم الباراميتر فقط‬
‫نوع الدالة مايهم‬

• You cannot overload a function name by giving two


definitions that differ only in the type of the value
returned. ‫ﯾﻌﻨﻲ ﻣﺎﺗﻌﺘﺒﺮ اوﻓﺮﻟﻮدﻧﻖ اذا ﺑﺲ اﻟﺮﯾﺘﺮن ﻣﺨﺘﻠﻒ‬

27
Overloading
First Example
Second

Second

First

28
Function Overloading (continued)

• Function overloading: creating several functions with


the same name 1

• The signature of a function


2
consists of the function
name and its formal parameter list Type of function doesn’t matter
• Two functions have different signatures if they have
– either different names or ‫اﻟﺴﻘﻨﺘﺸﺮ ﯾﺘﻀﻤﻦ اﺳﻤﮭﺎ واﻟﺒﺎراﻣﯿﺘﺮ‬
‫ﻓﻘﻄﻄﻄﻄﻂ ﻓﺒﯿﻜﻮن ﻣﺨﺘﻠﻒ اذا اﻻﺳﻤﺎء‬
– different formal parameter lists ‫ﻏﯿﺮ او اﻟﻔﻮرﻣﺎل ﺑﺎراﻣﯿﺘﺮ ﻏﯿﺮ‬

• Note that the signature of a function does not include


the return type of the function
‫اﻟﺴﻘﻨﺘﺸﺮ ﺣﻖ اﻟﻔﻨﻜﺸﻦ ﯾﺘﻀﻤﻦ اﺳﻤﮭﺎ‬
‫ﻣﺎﯾﺘﻀﻤﻦ اﻟﺮﯾﺘﺮن ﺗﺎﯾﺐ او ﻧﻮﻋﮭﺎ‬ ‫واﻟﺒﺎراﻣﯿﺘﺮ ﻓﻘﻄﻄﻄﻄﻂ‬

29
Define a function Call a function

function formal
return value type
name parameters
int z = max(i, j);
function int max( int num1, int num2)
header {
actual
int result; parameters
if (num1 > num2) function (arguments)
function result = num1; Signature
body else
result = num2;

return result; return


} Calling a function is equivalent
to execut ing the function body
Executing
Declare a function (prototype)

int max(int num1, int num2);

30
Function Overloading (continued)

• Correct function overloading:

• Syntax error:

Function signature must be different in


the function over loading

We don’t care about returning type


31
Automatic Type Conversion

• Given the definition


double mpg(double miles, double gallons)
{
return (miles / gallons);
}
what will happen if mpg is called in this way?
cout << mpg(45, 2) << “ miles per gallon”;
• The values of the arguments will automatically be
converted to type double (45.0 and 2.0)
If I called a function with parameters
of type double and I send arguments
with type int :
It will automatically converted to double

32
Type Conversion Problem
• Given the previous mpg definition and the following
definition in the same program
int mpg (int goals, int misses)
// returns the Measure of Perfect Goals
{
return (goals – misses);
}
what happens if mpg is called this way now?
cout << mpg(45, 2) << “ miles per gallon”;
– The compiler chooses the function that matches
parameter types, so the Measure of Perfect Goals will be
If I have 2 functions with same name but ( one
calculated double and the other int ), then I call a
function with arguments of type ( int ) the
program will choose the function int
Do not use the same function name for unrelated functions
‫ ﻋﺎدي ﺑﺘﺤﻮﻟﮭﺎ طﺒﯿﻌﻲ‬double ‫ وھﻲ‬int ‫ﯾﻌﻨﻲ ھﻮ ﻟﻮ ارﺳﻠﺖ ﻟﮭﺎ‬
int ‫ ﺑﯿﺨﺘﺎر اﻟﻔﻨﻜﺸﻦ‬int ‫ﺑﺲ ﻟﻮ ﻛﺎن اﻟﺒﺮوﻗﺮام ﻻزم ﯾﺨﺘﺎر ﺑﯿﻨﮭﻢ وھﻢ ﻧﻔﺲ اﻻﺳﻢ ﺣﺘﻰ ﻟﻮ ان ﺗﺎﯾﺐ اﻟﺒﺎراﻣﯿﺘﺮ ﻣﺨﺘﻠﻒ ﻻﻧﻨﻲ ﻛﺘﺒﺘﮭﺎ‬
33
CS221: Fundamentals of Programming

RECURSION AND RECURSIVE


FUNCTION
34
Recursive Functions
for Tasks
• A recursive function contains a call to itself
• When breaking a task into subtasks, it may be
that the subtask is a smaller example of the same
task
– Searching an array could be divided into searching the
first and second halves of the array
– Searching each half is a smaller version of searching the
whole array
– Tasks like this can be solved with recursive functions

35
Recursive Functions
for Tasks

Call to itself

36
Case Study:
Vertical Numbers
• Problem Definition:

– void write_vertical(int n);


//Precondition: n >= 0
//Postcondition: n is written to the screen vertically
// with each digit on a separate line

37
Case Study:
Vertical Numbers
• Algorithm design:
– Simplest case:
If n is one digit long, write the number
– Typical case:
1) Output all but the last digit vertically
2) Write the last digit

• Step 1 is a smaller version of the original task


• Step 2 is the simplest case

38
Case Study:
Vertical Numbers (cont.)
• The write_vertical algorithm:
if (n < 10) One digit only
{
cout << n << endl;
}
else // n is two or more digits long
{
It will call itself write_vertical(n with the last digit removed);

cout << the last digit of n << endl;


}

39
Case Study:
Vertical Numbers (cont.)
• Translating the pseudocode into C++
– n/10 returns n with the last digit removed
• 124/10=12 When divided by 10 the last digit removed

– n%10 returns the last digit of n


• 124%10=4 Module 10 will give us the last digit

• Removing the first digit would be just as valid


for defining a recursive solution
– It would be more difficult to translate into C++

40
Case Study:
Vertical Numbers
(cont.)

41
41
Case Study:
Vertical Numbers (cont.)

41
Tracing a Recursive Call

• write_vertical(123)
if (123 < 10)
{ cout << 123 << endl;
}

else Calls write_vertical(12)


// n is more than two digits We will send 12 to
{ the function

write_vertical(123/10);
cout << (123 % 10) << endl;
3
But it will not print unless we complete the first one which is 12
}

43
Tracing write_vertical(12)

• write_vertical(12)
if (12 < 10)
{ cout << 12 << endl;
}
else
// n is more than two digits Calls write_vertical(1)
{
We will send
1 to the
function
write_vertical(12/10);
cout << (12 % 10) << endl;
} 2

44
Tracing write_vertical(1)
• write_vertical(1)
if (1 < 10) Simplest case is now true
{ cout << 1 << endl;
}
Output 1
else
// n is more than two digits
{
write_vertical(1/10);
cout << (1 % 10) << endl;
}

45
A Closer Look at Recursion

• write_vertical uses recursion


– Used no new keywords or anything "new"
– It simply called itself with a different argument
• Recursive calls are tracked by
– Temporarily stopping execution at the recursive call
• The result of the call is needed before proceeding
– Saving information to continue execution later
– Evaluating the recursive call
– Resuming the stopped execution

46
How Recursion Ends

• Eventually one of the recursive calls must not


depend on another recursive call ‫الزم يكون عندي حالتني ع‬
‫االقل وحده تمر بدون الكول‬
• Recursive functions are defined as ‫والثانية تمر بشرط الكول‬

– One or more cases where the task is accomplished by


using recursive calls to do a smaller version of the task
– One or more cases where the task is accomplished
without the use of any recursive calls
• These are called base cases or stopping cases.
‫اﻟﺤﺎﻟﺔ اﻟﻠﻲ ﺗﺤﻘﻖ اﻟﺸﺮط وﻣﺎﺗﺮوح ﻟﻠﻜﻮل اﺳﻤﮭﺎ‬

47
"Infinite" Recursion
‫ﯾﻌﻨﻲ ﻣﺎﺗﺤﻘﻖ اﻟﺸﺮط اﺑﺪاااا‬

• A function that never reaches a base case, in


theory, will run forever
– In practice, the computer will often run out of resources
and the program will terminate abnormally
‫غير طبيعي‬

48
Example: Infinite Recursion

• Function write_vertical, without the base case


void new_write_vertical(int n)
{
new_write_vertical (n /10);
cout << n % 10 << endl;
}
will eventually call write_vertical(0), which will
call write_vertical(0), which will call
write_vertical(0) , which will call
write_vertical(0) , which will call
write_vertical(0) , which will call
write_vertical(0), which will call
write_vertical(0) , ………………………
49
Simple Example

With Loop With Recursion


int factorial (int n) int factorial (int n)
{ {
int answer = 1; if (n == 1)
for (int i=1; i<=n; i++) return 1;
answer *= i; else
return answer; return n*factorial(n-1);
} }

50
Factorial of 4
// Factorial of n = 1*2*3*...*n
#include <iostream>
using namespace std;
int factorial(int);
int main()
{
int n = 4;
cout << "Factorial of " << n <<" = " << factorial(n);
return 0;
}

int factorial(int n)
{
if (n > 1)
{
return n*factorial(n-1);
}
else
{return 1;}
}
51
Factorial of 4

52
Factorial of 4

53
Recursion
• What does the following function Do? Suppose
value of begin is 5
void printnum ( int begin )
{
cout<< begin;
if (begin< 9)
// The base case is when begin is greater than 9

printnum ( begin + 1 );
cout<< begin;
}
54
CS221: Fundamentals of Programming

SORT AND SEARCH WITH


FUNCTIONS AND RECURSION
55
Rewrite search and sort algorithms using functions

56
Pseudocode for Binary Search

57
Recursive Method for Binary Search

‫النها الزم تكون مرتبه‬

58
Execution of the Method search
(Part 1 of 2)

59
Execution of the Method search
(Part 1 of 2)

60
Checking the search Method

1. There is no infinite recursion


• On each recursive call, the value of first is increased,
or the value of last is decreased
• If the chain of recursive calls does not end in some
other way, then eventually the method will be called
with first larger than last -1

61
Checking the search Method

2. Each stopping case performs the correct action for


that case
• If first > last, there are no array elements
between a[first] and a[last], so key is not in
this segment of the array, and result is correctly set
to -1
• If key == a[mid], result is correctly set to mid

62
Checking the search Method

3. For each of the cases that involve recursion, if all


recursive calls perform their actions correctly, then
the entire case performs correctly
• If key < a[mid], then key must be one of the
elements a[first] through a[mid-1], or it is not
in the array
• The method should then search only those elements,
which it does
• The recursive call is correct, therefore the entire action
is correct

63
Checking the search Method

• If key > a[mid], then key must be one of the


elements a[mid+1] through a[last], or it is not in
the array
• The method should then search only those elements,
which it does
• The recursive call is correct, therefore the entire action
is correct
The method search passes all three tests:
Therefore, it is a good recursive method definition

64
Iterative Version of Binary Search
(Part 1 of 2)

65
Iterative Version of Binary Search
(Part 2 of 2)

66
References

• https://www.youtube.com/watch?v=czrbhZjp4JA
• https://www.youtube.com/watch?v=IAMzWp3kS_k
• https://www.youtube.com/watch?v=NvVYd08NUXI
• https://www.programiz.com/cpp-
programming/recursion

67
Any Questions

• Thanks for Listening J

68

You might also like