Chapter 01 - Functions
Chapter 01 - Functions
Miss:Hanan Hardan
1
Contents
Algorithm Design
Sub-Algorithms
C++ Functions
Definition
Types of Functions
Examples
Function Prototype
Scope of Variables
Call by Value / Call by Reference
2
Top-Down Algorithm Design
Topics to cover here:
Top-Down Design approach
Structured Programming
Sub-algorithms (a breadth look)
3
Top-Down Algorithm Design
1) Top-Down Design
The problem is divided into its major sub-problems
Solve the sub-problems to derive the solution to the
original problem.
2) Structured Design:
Dividing the problem into smaller sub-problems is called
“structured design”, “top-down design”,
“step-wise refinement”, and “modular Programming”
3) Structured Programming:
The process of implementing a structured design is called
“structured programming”
4
Structured Programming & Structure Chart
The main goal of structured programming is
to write error-free code
to reuse any possible code that has already been written and
tested (this is called reusability)
to have many sub-problems that are related.
5
Sub-algorithms
A sub-algorithm is a block of instructions that is executed
when it is called from some other point of the algorithm.
6
The Sub-algorithm Definition
a) Definition of a sub-algorithm that does not return a value
SUBALGORITHM subalgorithm-name ( )
Statements
END subalgorithm-name
7
The Sub-algorithm Definition
8
The Call to a Sub-algorithm
The call to a sub-algorithm that does not return a value is
given in the CALL statement which has the following syntax:
subalgorithm-name (Actual parameters)
Examples:
draw_circle ( )
sum(4,7)
sum(x,y)
9
The Call to a Sub-algorithm
Interpretation of the sub-algorithm call
Suppose that algorithm Figure calls the sub-algorithm
draw_circle using the call statement
CALL draw_circle ( )
Then the flow of control between sub-algorithms will be as
follows (see the next diagram):
10
The Call to a Sub-algorithm
Algorithm Figure Sub-algorithm draw_circle
ALGORITHM Figure call
------- SUBALGORITHM draw_circle ( )
------- ------
CALL draw_circle ( ) ------
------ ------
------ ------
------ END draw_circle
END Figure return
11
The Call to a function (C++)
program Figure Function draw_circle
13
Example 2:
Syntax ( in Algorithm ): Syntax ( in C++ ):
SubAlgorithm print_box ( n) void print_box (int n)
output “* * * * * * *\n” {
output “* “ , n , “ * \n” cout << “* * * * * * *\n” ;
output “* * * * * * *\n” cout << “* “ << n << “ * \n” ;
End print_box cout << “* * * * * * *\n” ;
}
Algorithm Test void main()
Begin {
Output “ Enter integer number" int a;
Input a cout<<"\n Enter integer number";
print_box (a) cin>>a;
print_box (5) print_box (a);
End Test cout<<endl;
print_box (5);
}
14
The Sub-algorithm Definition
b) Definition of a sub-algorithm that returns a value:
1- Sub-algorithm without arguments:
ftype SUBALGORITHM subalgorithm-name ( )
Statements
END subalgorithm-name
Notes:
- ftype: is any data type that the result of a subalgortihm can have.
If the subalgorithm does not return any result, then no type is
specified.
-( ) empty list.
- If the subalgorithm has a type, then the Statements in the body of
the subalgorithm should have return statement, usually it is the last
statement.
15
The Sub-algorithm Definition
b) Definition of a sub-algorithm that returns a value:
2- Sub-algorithm without arguments:
ftype SUBALGORITHM subalgorithm-name (parameter-list)
Statements
END subalgorithm-name
Notes:
- ftype: is any data type that the result of a subalgortihm can have.
If the subalgorithm does not return any result, then no type is
specified.
- parameter-list: includes one or more arguments.
- If the subalgorithm has a type, then the Statements in the body of
the subalgorithm should have return statement, usually it is the last
statement.
16
The Call to a Sub-algorithm
The call to a sub-algorithm that returns a value is given as
follows:
- The name of the sub-algorithm is given within the
OUTPUT statement
- The name of the sub-algorithm is given within the
assignment statement
Examples:
result Sum (x, y )
output Sum (x, y )
17
Example:
Syntax ( in Algorithm ): Syntax ( in C++ ):
INT SubAlgorithm sum () int sum ()
x5 {
y7 int x=5, y=7 ;
return x+y return x+y ;
End sum }
18
Example:
Syntax ( in Algorithm ): Syntax ( in C++ ):
INT SubAlgorithm Rect_area (L, W) int Rect_area (int L, int W)
aL*W {
return a int a ;
End Rect_area a=L*W;
return a ;
Algorithm Test }
Begin
Output “ Enter 2 integer number" void main()
Input a ,b {
Output “area==“, Rect_area(a,b) int a,b,z;
z Rect_area(3,2) cout<<"\n Enter 2 integer number";
Output “area=“ , z cin>>a>>b;
End Test cout<<“area==“<<Rect_area(a,b)<<endl;
z=Rect_area(3,2);
cout<<“area=“<<z<<endl;
}
19
Function - Summary
:Function Definition
User defined function is a code segment (block) that
.perform an specific action
Function Syntax:
Return_DT F_name ( list of formal parameters)
{
Action_ body ;
}
Types of Functions
Syntax:
void function-name ( )
{ local declarations // this is optional
executable statements
}
Example: function that doesn’t return a
value without arguments
void print_O ( )
{ cout << “ ** “ << endl;
cout << “ * * “ << endl;
cout << “ * * “ << endl;
cout << “ ** “ << endl;
}
Types of Functions
Syntax:
<any type> function-name( )
{ local declarations // this is optional
executable statements
}
Example: function that return a value without
arguments
int sum ()
{ int x=5, y=7 ;
return x+y ;
}
Types of Functions
Syntax:
<any type> function-name(argument_list )
{ local declarations // this is optional
executable statements
}
Example: function that return a value with
arguments
#include <iostream>
using namespace std;
int Max (int Value1, int Value2) { Function Definition
if (Value1 > Value2)
return Value1;
else
return Value2; Calling the function in an expression
} like cout<<, condition, assignment
statements
void main() {
int a, b;
cout<<"\nPlease Enter the values of a and b: ";
cin>>a>>b;
cout<<"\n the maximum one is: "<<Max(a,b)<<endl;
}
Example
#include <iostream>
using namespace std;
void main() {
int a, b, c;
cout<<"\nPlease Enter the values of a and b: ";
cin>>a>>b;
c=Max(a,b);
cout<<"\n the maximum one is: "<<c<<endl;
}
Example
#include <iostream>
using namespace std;
int Sum (int A, int B) {
return (A+B);
}
void main() {
int N1, N2, S;
cout<<"\n Please Enter N1 and N2: ";
cin>>N1>>N2;
S = Sum(N1,N2);
cout<<"\nSum= "<<S<<endl;
}
Example
#include <iostream>
using namespace std;
bool Positive (int Num) {
if (Num > 0)
return true;
else
return false;
}
void main() {
int Number;
cout<<"\nEnter Number: ";
cin>> Number;
if (Positive(Number))
cout<<"\n the number is positive";
else
cout<<"\n the number is negative";
cout<<endl;
}
Example
#include <iostream>
using namespace std;
float Area (int R) {
return (3.14 * R * R );
}
void main() {
int Radius;
cout<<"Enter the Redius: ";
cin>>Radius;
cout<<"\nCircle Area is: "<<Area(Radius);
cout<<endl;
}
Example
#include <iostream>
using namespace std;
long Power(int Base, int Exp) {
int M=1;
for(int i=1; i<=Exp; i++)
M*=Base;
return M;
}
void main() {
int B, E;
cout<<"\nEnter Base: ";
cin>>B;
cout<<"\nEnter Exponent: ";
cin>>E;
cout<<"\n Result= "<<Power(B,E);
cout<<endl;
}
Example
#include <iostream>
using namespace std;
long Fact (int Num) {
int F = 1, i = Num;
while (i>=1){
F *= i;
i--; }
return F;
}
void main() {
int Number;
cout<<"Enter an integer number: ";
cin>>Number;
cout<<endl<<Number<<"!= "<<Fact(Number);
cout<<endl;
}
Example
#include <iostream>
using namespace std;
void Print(char Ch, int n) { No Return
for (int i=1; i<=n; i++) Statement
cout<<Ch;
cout<<endl;
}
void main() {
char Sym;
int Number;
cout<<"\nEnter the Symbol: ";
cin>>Sym;
cout<<"\nHow many times: ";
cin>>Number;
Print(Sym,Number);
}
Example
#include <iostream>
using namespace std;
int Mul(int V1, int V2) {
return V1 * V2; }
void Result() {
cout<<"\n5 x 9 = "<<Mul(5,9);
cout<<"\n4 x 7 = "<<Mul(4,7);
cout<<"\n6 x 4 = "<<Mul(6,4)<<endl; }
void main() {
Result() ;
}
The Function Prototype
Like other identifiers in C++, function must be declared before it can be
referenced.
To declare a function, we can insert a function prototype before the main
function.
The function prototype provides all information that the C++ compiler
needs to know to translate calls to the function correctly.
void Show() {
int A=10, B=20;
cout<<Add(A,B)<<'\t'<<Mul(A,B)<<endl; }
Scope of Variables
// File: global.cpp
#include <iostream.h>
int x = 7 ; // global variables
int fun1 (int ); // function prototype
void main ( )
{ int z ; // local variable in main
cout << “The global variable: “ << x ;
z = fun1 ( 5 ) ; // calling add function
cout << “ The result is “ << z << endl ;
}
int fun1 ( int a )
{ int r ; // local variable in fun1
r= a*a*a;
return r ; }
Example2 of Local and Global Variables
#include <iostream>
using namespace std;
int x = 7; // global variable
void main() Output:
{
int x = 5; main 5
cout << "main "<< x<< endl; in block 3
{ global 7
int x = 3;
cout << "in block "<< x<< endl;
cout << "global "<< ::x<< endl;
}
}
More about global and local variables
#include <iostream.h>
void Increment(int);
void main() {
int A = 10;
Increment(A);
cout<<A<<endl;
}
#include <iostream.h>
void Increment(int&);
void main() {
int A = 10;
Increment(A);
cout<<A<<endl;
}
#include <iostream.h>
void Increment(int*);
void main() {
int A = 10;
Increment(&A);
cout<<A<<endl;
}
The output:
Enter two integers: 10 20
x = 10 y = 20
The result is 30
After call x = 10 y = 20
Example 2: Call by Reference
// File: calls2.cpp
#include <iostream.h>
// function prototype: the arguments to be passed by reference
void duplicate (int & , int & , int & );
void main ( )
{ int x, y , z ; // local variables in main
cout << “ Enter three integers: “ ;
cin >> x >> y >> z ;
cout << “ Before call: “ << “ x = “ << x << “ y = “ << y
<< “ z = “ << z <<endl;
duplicate ( x , y , z ) ; // calling duplicate function
cout <<“ After call: << “ x = “ << x << “ y = “ << y
<< “ z = “ << z <<endl;
}
void duplicate ( int & a , int & b , int & c )
{ a *= 2 ;
b *= 2 ;
c *= 2 ; }
Execution of Example 2
The user will be prompted to enter three integers.
The user enters, for example, 10, 20, and 30 that are saved in x, y,
and z respectively.
When function duplicate is called, the addresses of x, y, and z are
passed to the function.
The addresses of x, y, and z are linked to the parameters of the
function a, b, and c. The function will duplicate each parameter and
save the result in the same parameter. Thus,
a becomes 20 hence x becomes 20 also
b becomes 40 hence x becomes 40 also
c becomes 60 hence x becomes 60 also
After the call we see that the values of x, y, and z are changed.
The output:
Enter three integers: 10 20 30
Before call: x = 10 y = 20 z = 30
After call: x = 20 y = 40 z = 60
Overloading
Overloading, is the operation of defining
several functions of the same name, but in
different signatures.
54
Overloading – Example1
#include <iostream> void print (int x, char y)
using namespace std; {
void print () cout << "integer " << x<< " char " << y<< endl;
{ }
cout << "hello" << endl;
} void main()
{
void print (char x) print ();
{ print ('#');
cout << x << endl; print ('*', 5);
} print (2, '&');
}
void print (char a, int b)
{
for (int i=1; i<=b; i++) Output:
cout << a<<" "; hello
cout << endl;
}
#
*****
integer 2 char &
55
Overloading – Example2
#include <iostream> void main()
using namespace std; {
int a = 4, result;
int square (int x) float b = 5.5, result2;
{
return x * x; result = square (a);
} result2 = square (b);
Output:
Result = 16
Result2 = 30.25 56
Important Note - Overloading
Suppose you have defined these two In this case the compiler will result
functions: this syntax error:
int max (int x, int y) Cannot overload functions
{ distinguished by return type alone.
if (x > y)
return x;
else This means, that you cannot define
return y; the same function name twice or
} more, with the same number of
bool max (int a, int b) parameters and the same types, but
{ the only different is the return type.
if (a > b) There should be difference in the
return true; parameters as well.
else
return false;
}
57
Template
Assume you have this program:
void main()
#include <iostream> { Output:
using namespace std; swapping (2, 5);
void swapping (int a, int b) swapping ('$', '*'); 52
{
int temp;
}
*$
temp = a;
a = b; This is another example of
b = temp;
cout << a << " " << b<< endl; overloading, but you may
} need to add other functions
void swapping (char a, char b)
{
with other data
char temp; types as well.
temp = a; In such cases we can define a
a = b;
b = temp;
template function, that we can
cout << a << " " << b<< endl; send to it any data types we
}
need.
58
Template - Example
Assume you have this program:
Output:
#include <iostream> 52
using namespace std; 3.66 5.6
template <class T> void swapping (T a, T b)
*$
{ Ali Ahmad
T temp;
temp = a;
a = b; In this example, we only
b = temp;
cout << a << " " << b<< endl; needed to define the function
} swapping once, and we could
void main()
call it several types using
{ different data types for the
swapping (2, 5); parameters.
swapping (5.6, 3.66);
swapping ('$', '*');
swapping ("Ahmad", "Ali");
}
59
Template – Example2
#include <iostream>
using namespace std;
void main()
{
int x = square (2);
float y = square (3.5);
double z = square (556.98787);
long e = square (45268547);
61
Setting default values for
parameters in a function
Assume you have this program:
Output:
#include <iostream>
using namespace std;
@$%
void print (char x, char y, char z = ‘*’)
{
@$*
cout << x << " " << y << " "<< z;
}
void main()
{
print ('@', '$', '%');
print ('@', '$');
62
Setting default values for
parameters in a function
Assume you have this program:
Output:
#include <iostream>
using namespace std;
@$%
void print (char x, char y = ‘#’, char z = ‘*’)
{
@$*
cout << x << " " << y << " "<< z; @#*
}
void main()
{
print ('@', '$', '%');
print ('@', '$');
print ('@');
63
Setting default values for
parameters in a function
Assume you have this program:
Output:
#include <iostream>
using namespace std;
@$%
void print (char x = ‘&’, char y = ‘#’, char z = ‘*’)
{
@$*
cout << x << " " << y << " "<< z; @#*
}
&#*
void main()
{
print ('@', '$', '%');
print ('@', '$');
print ('@');
print ();
64
Setting default values for parameters in
a function – Example 2
Assume you have this program:
Output:
#include <iostream>
using namespace std;
@@@@@
void print (char x , int y =1)
{
#
for (int i=1; i<=y; i++)
cout << x <<" ";
cout << endl;
}
void main()
{
print ('@', 5);
print ('#');
65
Setting default values for parameters in
a function – Example 2
Suppose you have written the function print in the
following way:
Note here, that the first parameter
has a default value, while the second
void print (int y =1, char x ) doesn’t. C++ will not allow you do
{ order the parameters this way.
for (int i=1; i<=y; i++)
cout << x <<" ";
Always make sure that the
cout << endl; parameters with default values are
} listed at the end of the parameters.
66
Static Variables
67
Static Variables
Consider changing a little bit on the program, by Static keyword, that proceeds the declaration of
specifying the local variable x, as static.
the variable x, will expand its life time.
#include <iostream>
x is still a local variable that can be accessed
using namespace std;
only within the function test, but its lifetime won’t
end by the end of this function.
void test ()
{ The first time test() is called, x is declared and
static int x =1; initialized with 1, and then incremented.
x++;
The second time test() is called, x, won’t be
cout << "x = "<< x<< endl;
declared and initialized again, since it is static it
}
has reserved its final value in the previous call,
which was 2, so when it is incremented it will
void main()
Output: become 3.
{
test(); x=2
test(); x=3 The life time of a static variable, will end when
test(); x=4 the execution of the whole program is finished.
}
68
Recursion
69
Factorial example using loop
#include <iostream>
using namespace std;
void main ()
{
int y, fact =1;
cin >> y;
for (int i=y; i>=1; i--)
fact *=i;
cout << fact <<endl;
}
70
Factorial example using
Recursion
#include <iostream>
using namespace std;
int Fact (int N)
{
if (N<=1)
return 1;
else
return N * Fact(N-1);
}
void main() {
cout<<Fact(5)<<endl;
}
71
Example 2
#include <iostream>
using namespace std;
72
Example 3
#include <iostream>
using namespace std;
void exercise (int x)
{
if (x > 0 && x < 10)
{
cout << x << " ";
exercise (x + 1);
}
}
void main ()
{
exercise (5);
}
73
Example 4
Write a recursive function named,
sumSquares, that returns the sum of the
squares of the numbers from 0 to num, in
which num is a nonnegative int variable.
74
.Example 4: Cont
First, let’s solve this problem using For loop.
#include <iostream>
using namespace std;
void main ()
{ int num, sum = 0;
cin >> num;
for (int i=num; i>=0; i--)
sum = sum + i*i;
cout << "Sum = "<< sum << endl;
}
75
.Example 4: Cont
Now, solve the problem using recursive function.
#include <iostream>
using namespace std;
int sumSquare (int x)
{ if (x == 0)
return 0; // Base case #1
else
if (x == 1)
return 1; //Base case #2
else
return x * x + sumSquare (x-1);}
void main ()
{ int num;
cin >> num;
cout << "Sum = "<< sumSquare(num) << endl;
}
76
Homework
Q1: Write a recursive function that finds and
returns the sum of the elements in an int
array. Write a program to test your function.