0% found this document useful (0 votes)
8 views25 pages

Lec12 Functions 4

Chapter 6 focuses on functions, including writing various types of functions such as those for calculating factorials, checking positivity, and summing multiples. It also discusses recursion, reference parameters, and the differences between passing by value and passing by reference. Additionally, it provides examples of function implementations and emphasizes the trade-offs between recursion and iteration in programming.

Uploaded by

qwer353666
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)
8 views25 pages

Lec12 Functions 4

Chapter 6 focuses on functions, including writing various types of functions such as those for calculating factorials, checking positivity, and summing multiples. It also discusses recursion, reference parameters, and the differences between passing by value and passing by reference. Additionally, it provides examples of function implementations and emphasizes the trade-offs between recursion and iteration in programming.

Uploaded by

qwer353666
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/ 25

Chapter 6:

Functions

Copyright © 2012 Pearson Education, Inc.


Write the following functions
• Write a function that takes an integer as parameter and
prints its factors.

• Write a function that returns factorial of an integer value.

2 (C) Copyright 2019 by Prof.Abeer El_korany


Write the following functions
• Write a function that takes a string and an integer n as
parameters and returns that string repeated n times.

• Write a function isPositive that checks whether a number


(integer or float) is positive or not.

3 (C) Copyright 2019 by Prof.Abeer El_korany


Write the following functions
• Write a function that returns the sum of the first N
multiples of a number k:
k + 2*k + 3*k + 4*k +…………….+ N*k

4 (C) Copyright 2019 by Prof.Abeer El_korany


Functions 4
• Function call another
• Recursion
• Reference Parameters

5 (C) Copyright 2019 by Prof.Abeer El_korany


#include <iostream>
using namespace std;
void odd (int); void odd (int a)
void even (int ); {
if ((a%2)!=0)
int main () cout << "Number is
{ odd.\n";
int i; else even (a);
cout << "Type a }
number:";
cin >> i; void even (int a)
do { {
odd (i); if ((a%2)==0)
cout << "Type a cout << "Number is
number: (0 to exit)"; even.\n";
cin>>i; }
} while (i!=0);
return 0; Function call another function
}
6 (C) Copyright 2019 by Prof.Abeer El_korany
#include <iostream> return 0;
using namespace std; } //end of main
bool odd (int); bool odd (int a)
bool even (int ); {
if (!even(a))
int main ( )
return true;
{ else return false;
int i; }
cout << "Type a number:
"; bool even (int a)
cin>>i; {
if ((a%2)==0)
do { return true;
cout<<(odd(i)?″Odd‶:″Even‶); else
cout << "Type a number: return false;
(0 to exit)"; }
cin>>i; Function returning boolean
} while (i!=0);
7 (C) Copyright 2019 by Prof.Abeer El_korany
Exercise
• Write 2 functions getTotal and getAvg.
The function getTotal returns the total of
3 input numbers, while getAvg returns
the average of 3 input numbers. Make
use of getTotal in the function getAvg.
In main read 3 doubles from the user and
print their average by calling the function
getAvg.

8 (C) Copyright 2019 by Prof.Abeer El_korany


Recursion
• Recursive functions
– Functions that call themselves
• In some problems, it may be natural to define the problem in
terms of the problem itself.
• Recursion is useful for problems that can be represented by a
simpler version of the same problem.
• Example: the factorial function
6! = 6 * 5 * 4 * 3 * 2 * 1
We could write:
6! = 6 * 5!
– Can only used to solve a base case
– Base case (1! = 0! = 1)

9 (C) Copyright 2019 by Prof.Abeer El_korany


factorial function
• Assume the number typed is 3, that is, numb=3.
fac(3) :

3 <= 1 ? No.
fac(3) = 3 * fac(2)
fac(2) :
2 <= 1 ? No.
fac(2) = 2 * fac(1)
fac(1) :
1 <= 1 ? Yes.
return 1 int fac(int numb){
fac(2) = 2 * 1 = 2 if(numb<=1)
return fac(2) return 1;
fac(3) = 3 * 2 = 6 else
return fac(3) return numb * fac(numb-1);
}
fac(3) has the value 6
(Factorial) Function Recursion (cont)
#include <iostream>
using namespace std;
int fact(int num)
{
if(num >1 )
return num * fact(num-1);
else
return 1;
}
int main()
{
int n;
cout << "enter an integer ";
cin >> n;
int x = fact(n);
cout << "factorial of " << n <<" is "<<x<< endl;
return 0;
} (C) Copyright 2019 by Prof.Abeer El_korany
11
factorial function
For certain problems (such as the factorial function), a recursive
solution often leads to short and elegant code. Compare the
recursive solution with the iterative solution:

Recursive solution Iterative solution


int fac(int numb){ int fac(int numb){
if(numb<=1)
int product=1;
return 1;
else while(numb>1){
return numb*fac(numb-1); product *= numb;
} numb--;
}
return product;
}
#include <iostream>
Function Recursion (cont)
using namespace std;
double power(int val, int pow)
{
if(pow == 0)
return(1.0);
else
return(power(val, pow - 1) * val);
}
int main()
{
int n,m;
cout << "enter an integer ";
cin >> n;
cout << "enter power ";
cin >> m;
double x = power(n,m);
cout << " power of \t" << n << " and " <<m<<" is \t"<<x<< endl;
} (C) Copyright 2019 by Prof.Abeer El_korany
13
#include <iostream> Function Recursion (cont)
using namespace std;
double power(int val, int pow)
{
if(pow == 0)
return(1.0);
else if (pow>1)
return(power(val, pow - 1) * val);
else
return(power(val, pow + 1) / val);
}
int main()
{
int n,m;
cout << "enter an integer ";
cin >> n;
cout << "enter power ";
cin >> m;
double x = power(n,m);
cout << " power of \t" << n << " and " <<m<<" is \t"<<x<< endl;
} (C) Copyright 2019 by Prof.Abeer El_korany
14
Recursion
We have to pay a price for recursion:
– calling a function consumes more time and memory
than adjusting a loop counter.
– high performance applications (graphic action
games, simulations of nuclear explosions) hardly
ever use recursion.

In less demanding applications recursion is an


attractive alternative for iteration (for the right
problems!)
Recursion vs. Iteration
• Repetition
– Iteration: explicit loop
– Recursion: repeated function calls
• Termination
– Iteration: loop condition fails
– Recursion: base case recognized
• Both can have infinite loops
• Balance between performance (iteration) and
good software engineering (recursion)
16 (C) Copyright 2019 by Prof.Abeer El_korany
Recursion Example
Write a recursive function that repeats a string s,
for n times.
int main( )
{
string s=“hello”;
cout<<repeat(s, 5);
//output should be “hellohellohellohellohello”
return 0;
}

17 (C) Copyright 2019 by Prof.Abeer El_korany


Reference Parameters
• If the formal argument declaration is a reference
parameter then
– Formal parameter becomes an alias for the actual
parameter
• Changes to the formal parameter change the actual parameter
• Function definition determines whether a
parameter’s passing style is by value or by
reference
– Reference parameter form
– Type &pname

• void swap(int &a, int &b)

18 (C) Copyright 2019 by Prof.Abeer El_korany


Passing by Reference
• A reference variable is an alias for another
variable
• Defined with an ampersand (&)
void getDimensions(int&, int&);
• Changes to a reference variable are made to
the variable it refers to
• Use reference variables to implement
passing parameters by reference

19 (C) Copyright 2019 by Prof.Abeer El_korany


Function call by value
#include <iostream>
using namespace std;
void Swap(int, int );
int PromptAndRead();
int main() {
int Number1 = PromptAndRead();
int Number2 = PromptAndRead();
if (Number1 > Number2) {
Swap(Number1, Number2);
}
cout << "The numbers in sorted order:"
<< Number1 << ", " << Number2 << endl;
return 0;
}

void Swap(int a, int b) {


int Temp = a;
a = b;
b = Temp;
}
20 – Changes to the formal parameter
(C) Copyright
does not2019 by the
change Prof.Abeer El_korany
actual parameter
#include <iostream> Function call by reference
using namespace std;
void Swap(int &, int &);
int PromptAndRead();
int main() {
int Number1 = PromptAndRead();
int Number2 = PromptAndRead();
if (Number1 > Number2)
Swap(Number1, Number2);
cout << "The numbers in sorted order: "
<< Number1 << ", " << Number2 << endl;
return 0;
} int i = 5;
void Swap(int &a, int &b) int j = 6;
{
int Temp = a; Swap(i, j);
a = b;
b = Temp;
int a = 7;
} int b = 8;
Swap(b, a);
21 (C) Copyright 2019 by Prof.Abeer El_korany
Function call by reference (cont)
#include <iostream>
using namespace std;
void doubleNum(int &);
int main()
{
int value = 4;
cout << "In main, value is " << value << endl;
cout << "Now calling doubleNum..." << endl;
doubleNum(value);
cout << "Now back in main. value is " << value << endl;
return 0;
}

void doubleNum(int &refVar)


{
refVar *= 2;
}
22 (C) Copyright 2019 by Prof.Abeer El_korany
Function call by reference (cont.)

#include <iostream> (return more than one value)


using namespace std;
void duplicate(int& a, int& b, int& c)
{
a*=2;
b*=2;
c*=2;
}
int main ()
{
int x=1, y=3, z=7;
duplicate (x, y, z);
cout << "x=" << x << ", y=" << y << ", z=" << z;
return 0;
}
23 (C) Copyright 2019 by Prof.Abeer El_korany
Function call by reference (cont.)

#include <iostream> (return more than one value)


Using namespace std;
void prevnext (int x, int& prev, int& next)
{
prev = x-1;
next = x+1;
}
int main ()
{
int x=100, y, z;
prevnext (x, y, z);
cout << "Previous=" << y << ", Next=" << z;
return 0;
}

24 (C) Copyright 2019 by Prof.Abeer El_korany


Reference Variable Notes
• Each reference parameter must contain &
• Space between type and & is unimportant
• Must use & in both prototype and header
• Argument passed to reference parameter must be a variable –
cannot be an expression or constant
• Use when appropriate – don’t use when argument should not
be changed by function, or if function needs to return only 1
value

25 (C) Copyright 2019 by Prof.Abeer El_korany

You might also like