SlideShare a Scribd company logo
User-defined functions
Ali Alsbou
functions : Part II
Introduction :
• A complex program is often easier to solve by dividing it
into several smaller parts, each of which can be solved by
itself This is called structured programming.
• These parts are sometimes made into functions in C++.
• All C++ programs must contain the function main( ).
• The execution of the program starts from the function
main( )
2
C++
Programming,
Ali
Alsbou
Advantages of Functions
• Functions make programs easier to write, debug,
and understand.
• Functions can be called several times in the same
program, allowing the code to be reused.
3
C++
Programming,
Ali
Alsbou
Need to know
• Functions invoked by a function–call-
statement which consist of it’s name and
information it needs (arguments)
functionName (argument);
• All other functions are directly or
indirectly called from main.
• The purpose of a function is to receive
data, process it and return a value to the
function which has called it.
4
C++
Programming,
Ali
Alsbou
User-defined functions
• Standard C++ Library is still not sufficient for
most programming tasks.
• Programmers also need to be able to define
their own functions
5
C++ Programming, Ali Alsbou
function–call Principle
• Boss To Worker
A Boss (the calling/caller function) asks a worker (the
called function) to perform a task and return result when it
is done.
6
7
C++ program Flow of Control
The following diagram shows how the flow control
of a program is changed by functions.
Note: usual main( ) Calls other
functions, but other functions
can call each other
C++
Programming,
Ali
Alsbou
Function Definitions :
How to write :
8
Function definition format
return-value-type function-name( type parameter-list )
{
declarations and statements
return;
}
1) Return-value-type: data type of the result (default int)
void – indicates that the function returns nothing
2) Function-name: any valid identifier
3) Parameter-list: comma separated list, declares parameters
A type must be listed for each parameter
The function header
2 3
4
5
1
C++ Programming, Ali Alsbou
Each function has its own
name. Function name
follows rules of naming
identifiers as variables
and constants
Function definition format
return-value-type function-name( type parameter-list )
{
declarations and statements
return;
}
4) function body (block)
 Variables can be defined inside blocks (can be nested)
 Functions can not be defined inside other functions
5) Returning control :Function return ONLY one value
If nothing returned
• return;
• or, until reaches right brace
If something returned
• return expression;
4
5
Function return value types
10
int f1(Parameter List)
{
return value ;
}
void f2(Parameter List)
{
return; // nothing returned
}
void f2(Parameter List)
{
// nothing returned
}
If return type is
missing, it means int.
f2(Parameter List)
{
}
1
3
4
2
C++ Programming, Ali Alsbou
void Function
A function that is not
supposed to return a
value(RETURN result)
has a return type of
void.
Function Parameters
• The purpose is to allow passing arguments to the function from the
location where it is called from.
• Parameters declared in the function header within parenthesis
• Either have a single, multiple parameters or have no parameters
• List of a parameters are separated by commas
• Each parameter must be defined as follows
DataType parameterName
• Note : The parameters may or may not be altered by the function.
11
char f1(int x, int y)
{
return value ;}
C++ Programming, Ali Alsbou
Exercises(1)
• Write C++ functions that :
• Find summation of two integer number(as parameters) and
return result.
• Find subtraction of two integer number(as parameters) and
return result.
• simply prints any message.
Examples (1)
13
C++ Programming, Ali Alsbou
Example (2)
14
Write a function to compute n!
C++ Programming, Ali Alsbou
General form of C++ program with functions
15
The function definition can be placed anywhere in the
program after the function prototypes.
C++ Programming, Ali Alsbou
Function Prototypes(declaration)
• Prototype only needed if function definition comes after use in program
• Alternative to Prototype is to place function definition before main() function
• Write the Function prototype after include<> statements, and before main
function.
• Function prototype statement is a function definition header
terminated by the semicolon;
• The general form of the declaration is
Return_ type function_ name ( parameter_ list );
 Prototype must match function definition header
int square(int y);
16
C++ Programming, Ali Alsbou
int square(int);
Note : The variables in the
function declaration can be
optional but data types are
necessary
Function prototype : Con’t
• Function Definition
double maximum(double x,double y,double z)
{
… }
• Function prototype
double maximum(double x,double y,double z);
Or
double maximum(double , double , double );
17
C++ Programming, Ali Alsbou
Example (3) : Function Prototypes
1. double CircleArea(double radius);
2. double CircleArea(double);
3. int calculation(int n,float j);
4. int calculation (int,float);
5. int calculation (int n,float);
6. double computeTax(double income);
18
C++ Programming, Ali Alsbou
Using Function
How Function Call Works
19
Functions invoked by a function–call-statement which consist of it’s name and
information it needs (arguments)
functionName (argument);
 Each value passed in a function call is referred to as an Argument
- Arguments may be constant value ,variable or expression
 Arguments passed by value and by reference (later .)
 Arguments (Passed in a Function call) and parameters (defined in a function
header) MUST match in: Number , Order and Data types
void Display_Msg(int x)
{
if (x > 60)
cout<<"You passed";
else
cout<<“You failed";
}
int main()
{
Display_Msg(87);
return 0;
}
Argument
Parameter
C++ Programming, Ali Alsbou
Using Function
How Function Call Works – Cont.
20
C++ Programming, Ali Alsbou
if function return value:
int func1(int value)
{
result=value;
return result;
}
Use func. Calling statement with :
- Variable Ex. x= func1(3);
- output statement Ex. cout<< func1(3)
- Expression Ex. x=func1(3)+5- func1(4);
Function–call-statement
Example
21
C++ Programming, Ali Alsbou
function–call-statement:
• cout<<square (2);
• cout<<square (2+6);
• y=2;
X= square (y); // X= 4
• if (square (y) > 2) cout <<“True”;
• for( int c=0; c> square (2);c--) …..
Function–call-statement
Example
• if function return nothing (void function):
void func1(int value)
{
result=value;
return; // or no need to write this
}
• Use func. Calling statement like:
func1(3); //since this function return nothing
Function Call Methods
Passing mechanism
Two ways to pass arguments to functions
• Call by value
• Call by reference (memory locations )
 Mixed Methods
Parameter lists can include pass-by-value and pass-by-reference parameters
23
C++ Programming, Ali Alsbou
Call by value
 A copy of the value is passed
 a copy of the parameters value is taken from the calling function
and passed to the called function
 Suppose that :
void exam(int b); func. Prototype
a=27;
exam(a); func. calling
24
All the pervious examples used this method
27 27
a
b
B=b++;
27 28
a b
copy of a
C++ Programming, Ali Alsbou
Example (4)
 a copy of the parameters value is
taken from the calling function and
passed to the called function
Example(5)
Example(6)
1.// Creating and using a programmer-defined function.
2.#include <iostream.h>
3. int square( int ); // function prototype
4. int main( ) {
1.for ( int x = 1; x <= 10; x++ )
2.cout << square( x ) << " "; // function call statement
3.cout << endl;
4.return 0; // indicates successful termination
5. } // end main
6.int square( int y ) // y is a copy of argument to function
7. {
8. return y * y; // returns square of y as an int
9. } // end function square
27
1 4 9 16 25 36 49 64 81 100
C++ Programming, Ali Alsbou
Example(7)
Write a program to find the average of three integer marks (use functions)?
28
#include<iostream.h>
float avg(int,int,int); //function prototype
main() {
int m1,m2,m3;
cout <<"Enter three marks :";
cin>>m1>>m2>>m3;
cout <<"The average is : "<<
avg(m1,m2,m3); //function calling
}
float avg(int a,int b , int c) //function definition
{
float d;
d=(a+b+c)/3.0;
return d;
}
C++ Programming, Ali Alsbou
Example(8)
#include<iostream.h>
int max (int a,int b,int c);
main() {
int x,y,z,m;
cout <<"Enter three numbers :";
cin>>x>>y>>z;
m = max(x,y,z);
cout <<"the maximum number is "<< m;
}
int max (int a,int b,int c) {
int m=a;
if (m<b) m=b;
if (m<c) m=c;
return m; }
29
#include<iostream.h>
int max (int a,int b,int c)
{
int m=a;
if (m<b) m=b;
if (m<c) m=c;
return m;
}
main()
{
int x,y,z,m;
cout <<"Enter three numbers :";
cin>>x>>y>>z;
m = max(x,y,z);
cout <<"the maximum number is "<< m;
}
1 2
C++ Programming, Ali Alsbou
Example (9)
Write C++ program, using function, to find the summation of
the following series:
30
#include<iostream.h>
int summation ( int x)
{
int i = 1, sum = 0;
while ( i <= x )
{
sum += i * i ;
i++;
}
return (sum);
}
main ( )
{
int n ,s;
cout << "enter positive number"
cin >> n;
s = summation ( n );
cout << "sum is: " << s << endl;
}
C++ Programming, Ali Alsbou
Example(10)
void Function take no arguments
If the function Does Not Take
Arguments specify this with
EMPTY-LIST OR write void
inside
#include<iostream.h>
void funA();
void funB(void)
main()
{
funA();
funB();
return 0; }
void funA()
{ cout << "Function-A takes no arqumentsn"; }
void funB()
{ cout << "Also Function-B takes No argumentsn"; }
C++ Programming, Ali Alsbou
Will be the same
in all cases
Example(11)
#include <iostream.h>
void even (int);
main() {
for( int i=20;i<35;i++)
even(i);
}
void even (int x) {
if(x %2==0)
cout<<x<<" "; }
32
Print the even numbers between (20,35) using function void even (int);
C++ Programming, Ali Alsbou
Call by reference
• This method is more efficient and provides
higher execution speed than the call by value
method, but call by value is more direct and
easy to use.
• gives the called function the ability to directly
access the caller’s value, and to modify it.
33
C++ Programming, Ali Alsbou
Call by reference
• The argument to a reference parameter must be a
variable, not a constant or an expression
• "address of " actual argument is passed
• The parameter in function definition must be
prefixed with ampersand(&)
void fname (type &);// prototype
main()
{
fname(argument);
}
void fname(type &parameter_name)
{
… }
// passing address of argument
Example(12)
#include <iostream.h>
void increment (int );
int main ()
{
int a=5;
increment(a);
cout<<a<<endl;
return 0;
}
void increment (int z) 35
#include <iostream.h>
void increment (int &);
int main ( )
{
int a=5;
increment(a);
cout<<a<<endl;
return 0;
}
void increment (int &z)
{ z++; }
Call by reference
Call by value
//Value a is copied to z;
C++ Programming, Ali Alsbou
Example(13)
#include<iostream>
int square(int); //prototype call by value function
void squarref(int &); // prototype call by –reference function
int main()
{
int x=2, z=4;
cout<< "x=" <<x << " before calling squareVal"<<endl;
square(x) ; // call by value
cout<< "x=" <<x << " After returning"<<endl;
cout<< "z=" <<z << " before calling squareRef"<<endl;
squarref(z); // call by reference
cout<< "z=" <<z<< " After returning squareRef"<<endl;
return 0;
}
36
void square(int a)
{
a*=a;
// caller’s argument not modified
}
void squarref(int &cRef)
{
cRef *= cRef;
// caller’s argument modified
}
C++ Programming, Ali Alsbou
Example(14):
swap Function
// swap() function definition
void swap(double & num1, double &
num2)
// swap the values of num1 and num2
{
double temp;
temp = num1; // Why do we need temp?
num1 = num2;
num2 = temp;
}
37
swap(oneNum, anotherNum);
C++ Programming, Ali Alsbou
Example(15)
#include<iostream.h>
float rectangle(float width, int &height)
{
float area; // Area of the rectangle
area = width * height ;
return (area);
}
int main()
{ int h=3;
float area=rectangle(2,h);
cout<< area;
return 0; } 38
C++ Programming, Ali Alsbou
Illegal function Call
Void calc(double l,double w,double & a,double & p);
Suppose that :
double a =3.0,b=4.0,c=5.0,d= 6.0,e=7.0;
const double x = 5.0, y = 6.0;
The following function calls are illegal:
• calc(3.0, 4.0, 5.0, 6.0);
• calc(a, b, 5.0, 6.0);
• calc(a, b, c*d, e);
• calc(a, b, x, y);
39
C++ Programming, Ali Alsbou
Exercise(2)
Suppose that :
double circleArea(double & radius);// Pass by reference
double r=2.5;
Where is the errors in the following statements?
area1 = circleArea(3*r+2.0);// SYNTAX ERROR!
area2 = circleArea(3.5); // SYNTAX ERROR!
40
C++ Programming, Ali Alsbou
Global vs. local variables
41
C++ Programming, Ali Alsbou
Global vs. local variables
Scope of variable :
• A scope (the part of the program code that can use it)
Global variables :
• defined outside and before function main:
• all functions can see it and using it and can be
accessible and used anywhere in the entire program.
(Scope)
• Global variables can live as long as the program is
executed
42
C++ Programming, Ali Alsbou
Example(16)
Global variables :
#include <iostream.h>
int x = 0; // global variable
void f1( )
{ x++; }
void f2( )
{
x+=4;
f1( );
}
main( ) {
f2( );
cout << x << endl; }
43
C++ Programming, Ali Alsbou
Local variables :
• Local variables are declared inside the function body
and exist as long as the function is running and
destroyed(de-allocated) when the function exit
• You have to initialize the local variable before using it
• If a function defines a local variable and there was a
global variable with the same name, the function
uses its local variable instead of using the global
variable
• A local variable can be used only in the function
where it is defined
44
C++ Programming, Ali Alsbou
Example(17)
#include <iostream.h>
int x=99; // Global variable
Void fun();
void main()
{
int x = 4; // loacl variable
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;}
45
C++ Programming, Ali Alsbou
Example(18)
#include<iostream.h>
int x,y; //Global Variables
int add2(int, int);
main()
{ int s;
x = 11;
y = 22;
cout << "global x=" << x << endl;
cout << "Global y=" << y << endl;
s = add2(x, y);
cout <<x <<"+" << y << "=" << s;
cout<<endl;
cout<<"n---end of output---n";
return 0; }
46
int add2(int x1,int y1)
{
int x; //local variables
x=44;
cout << "nLocal x=" << x << endl;
return x1+y1;
}
C++ Programming, Ali Alsbou
Example(19)
#include<iostream.h>
void f(void);
main ( )
{
f();
f();
f();
}
void f(void)
{
int x=0;
x++;
cout<<x<<endl;
}
47
C++ Programming, Ali Alsbou
Static vs. Automatic variables
• Normal” local variables go out of scope and are de-
allocated when a function terminates.
• Static variables remain and retain their value.
• Format:
• When declare static variable it initializes to 0 unless
you specify another value
48
void f( )
{
static <variable_type> <variable_name>
…
}
C++ Programming, Ali Alsbou
Example(21)
void my_function ( )
{
int count = 1;
cout<<"this function has been called "<<count<<"n";
count++;
return;
}
int main(){
my_function();
my_function();
my_function();
return 0; }
49
C++ Programming, Ali Alsbou
Example(21)- Cont.
void my_function ( )
{
static int count = 1;
cout<<"this function has been called "<<count<<"n";
count++;
return;
}
int main(){
my_function();
my_function();
my_function();
return 0;}
50
C++ Programming, Ali Alsbou
Example(22)
#include <iostream>
void showstat( int curr )
{
static int nStatic;
nStatic += curr;
cout << "nStatic is " << nStatic << endl;
}
int main()
{
for ( int i = 0; i < 4; i++ )
showstat( i );
}
51
nStatic is 0
nStatic is 1
nStatic is 3
nStatic is 6
C++ Programming, Ali Alsbou
Arrays &Functions
52
C++ Programming, Ali Alsbou
Passing Arrays to Functions
• To pass an array argument to a function
Specify array name without brackets
Array a is declared as
int a[ 24 ];
The function call
modifyArray( a, 24 );
passes array a and its size to function modifyArray
• Array size is normally passed as another argument
so the function can process the specific number of
elements in the array
• Arrays are passed by reference (Function call actually passes starting
address of array )
53
C++ Programming, Ali Alsbou
Passing Arrays to Functions (Cont.)
• Individual array elements passed by value
Use the subscripted name of the array element as an argument
Example:
modifyElement( a[ 3 ] );
void modifyElement( int e )
{
cout << "Value of element in modifyElement: " << ( e *= 2 ) << endl;
}
54
Function Calling
Function definision
C++ Programming, Ali Alsbou
Functions that take arrays as arguments
• Function definition
Example:
void modArray( int b[], int arraySize );
• Array parameter may include the size of the array
• Compiler will ignore it, though Compiler only cares about
the address of the first element
55
C++ Programming, Ali Alsbou
Exercise(3)
Using function, write a program to read array items then print them
56
#include<iostream.h>
void read (int [],int);
void print(int [],int);
main()
{
int R[5];
read (R,5);
print(R,5);
} void print (int F[],int x)
{
int i;
for(i=0;i<x;i++)
cout<<F[i]<<" ";
}
void read (int M[],int n)
{
int i;
for(i=0;i<n;i++)
{
cout <<"Enter item number "<<i<<" : ";
cin>> M[i];
} }
C++ Programming, Ali Alsbou
Passing 2D-array to function
you must determine the size of column in two
dimension array
57
C++ Programming, Ali Alsbou
Example(23)
#include<iostream.h>
void printArray (int [][3]) ;
int main ( )
{
int array1[2][3]={{1,2,3},{4,5,6}};
cout<<"Array1=";
printarray(array1);
}
void printarray (int a[][3])
{
for (int i=0 ; i<2 ; i++)
{
for (int j=0 ; j<3 ; j++)
cout<<a[i][j];
cout<<endl;
} } 58
C++ Programming, Ali Alsbou
Recursive Function ( Recursion) :
A function that calls itself
A recursive function has two parts:
1) the terminal/base case.
a stopping condition
2) the reducing case/recursive step
an expression of the computation or definition in terms of itself
Every recursive call reduces the original problem,
bringing it increasingly closer to a base case until it
becomes that case.
59
C++ Programming, Ali Alsbou
General algorithm for recursion
60
if (terminal_condition)
terminal_case
else
reducing_case
if (!terminal_condition)
reducing_case
C++ Programming, Ali Alsbou
Example(24):
print numbers counting down
# include<iostream>
void print(int n)
{
if (n==0)
return;
cout<<n<<endl;
print(n-1);
}
61
int print2(int n)
{
if (n==0)
return 1;
cout<<n<<endl;
return print2(n-1);
}
C++ Programming, Ali Alsbou
main( )
{
int n;
cin>>n;
print(n);
cout<<print2(n);
}
Factorials by recursion
• Easy way to calculate n!
• n! = 1 if n == 1 or n==0
• Otherwise, n! = n * (n-1)!
62
C++ Programming, Ali Alsbou
Example(25):
Factorials by recursion – Cont.
#include<iostream.h>
int factorial (int n);
main ( )
{ int n;
cin>>n;
cout<<factorial(n); }
int factorial (int n)
{
if (n==1 || n==0) // base case
return 1;
else
return n * factorial(n-1); // recursive part
}
63
recursive step
terminal_case
C++ Programming, Ali Alsbou
Recursive function
Find X to the power n
• Terminal case
if n==0 since x to powr 0 is =1
• Recursive case
x * power(x,n-1)
64
C++ Programming, Ali Alsbou
Example(26)
65
C++ Programming, Ali Alsbou
#include<iostream.h>
int power (int x , int n );
main ( ) {
int x,y;
cout<<"enter two numbern";
cin>>x>>y;
cout<<power(x,y);}
int power (int x, int n )
{
if (n==0)
return 1; // base case
else
return x* power(x,n-1); // recursive part
}
Example(27):
66
C++ Programming, Ali Alsbou
Write a recursive function to find the sum of the first 4 elements of an
integer array "a[ ]".
Example(28)
Note about recursion function
• Infinite recursion
Any recursive function that not bringing it to a base
case
68
C++ Programming, Ali Alsbou
Ad

More Related Content

Similar to Chp8_C++_Functions_Part2_User-defined functions.pptx (20)

Function
Function Function
Function
Kathmandu University
 
Functions in C-csvsvvcvxcvxvxcvxcvvsvsvsfvsfvd
Functions in C-csvsvvcvxcvxvxcvxcvvsvsvsfvsfvdFunctions in C-csvsvvcvxcvxvxcvxcvvsvsvsfvsfvd
Functions in C-csvsvvcvxcvxvxcvxcvvsvsvsfvsfvd
scs150831
 
Functions struct&union
Functions struct&unionFunctions struct&union
Functions struct&union
UMA PARAMESWARI
 
Silde of the cse fundamentals a deep analysis
Silde of the cse fundamentals a deep analysisSilde of the cse fundamentals a deep analysis
Silde of the cse fundamentals a deep analysis
Rayhan331
 
Function in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programmingFunction in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programming
estorebackupr
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
sangeeta borde
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
Mohammed Saleh
 
Function
FunctionFunction
Function
yash patel
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
WaheedAnwar20
 
9 functions.pptxFunction that are used in
9 functions.pptxFunction that are used in9 functions.pptxFunction that are used in
9 functions.pptxFunction that are used in
divyamth2019
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
KhurramKhan173
 
Learning C++ - Functions in C++ 3
Learning C++ - Functions  in C++ 3Learning C++ - Functions  in C++ 3
Learning C++ - Functions in C++ 3
Ali Aminian
 
4th unit full
4th unit full4th unit full
4th unit full
Murali Saktheeswaran
 
Functions
FunctionsFunctions
Functions
Pragnavi Erva
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Nikhil Pandit
 
6. Functions in C ++ programming object oriented programming
6. Functions in C ++ programming object oriented programming6. Functions in C ++ programming object oriented programming
6. Functions in C ++ programming object oriented programming
Ahmad177077
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
Sampath Kumar
 
Funtions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the topsFuntions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the tops
sameermhr345
 
1.6 Function.pdf
1.6 Function.pdf1.6 Function.pdf
1.6 Function.pdf
NirmalaShinde3
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
Aiman Hud
 
Functions in C-csvsvvcvxcvxvxcvxcvvsvsvsfvsfvd
Functions in C-csvsvvcvxcvxvxcvxcvvsvsvsfvsfvdFunctions in C-csvsvvcvxcvxvxcvxcvvsvsvsfvsfvd
Functions in C-csvsvvcvxcvxvxcvxcvvsvsvsfvsfvd
scs150831
 
Silde of the cse fundamentals a deep analysis
Silde of the cse fundamentals a deep analysisSilde of the cse fundamentals a deep analysis
Silde of the cse fundamentals a deep analysis
Rayhan331
 
Function in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programmingFunction in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programming
estorebackupr
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
sangeeta borde
 
9 functions.pptxFunction that are used in
9 functions.pptxFunction that are used in9 functions.pptxFunction that are used in
9 functions.pptxFunction that are used in
divyamth2019
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
KhurramKhan173
 
Learning C++ - Functions in C++ 3
Learning C++ - Functions  in C++ 3Learning C++ - Functions  in C++ 3
Learning C++ - Functions in C++ 3
Ali Aminian
 
6. Functions in C ++ programming object oriented programming
6. Functions in C ++ programming object oriented programming6. Functions in C ++ programming object oriented programming
6. Functions in C ++ programming object oriented programming
Ahmad177077
 
Funtions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the topsFuntions of c programming. the functions of c helps to clarify all the tops
Funtions of c programming. the functions of c helps to clarify all the tops
sameermhr345
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
Aiman Hud
 

Recently uploaded (20)

libbys peer assesment.docx..............
libbys peer assesment.docx..............libbys peer assesment.docx..............
libbys peer assesment.docx..............
19lburrell
 
IMPACT_OF_SOCIAL-MEDIA- AMONG- TEENAGERS
IMPACT_OF_SOCIAL-MEDIA- AMONG- TEENAGERSIMPACT_OF_SOCIAL-MEDIA- AMONG- TEENAGERS
IMPACT_OF_SOCIAL-MEDIA- AMONG- TEENAGERS
rajaselviazhagiri1
 
Conditions for Boltzmann Law – Biophysics Lecture Slide
Conditions for Boltzmann Law – Biophysics Lecture SlideConditions for Boltzmann Law – Biophysics Lecture Slide
Conditions for Boltzmann Law – Biophysics Lecture Slide
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
"Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit...
"Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit..."Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit...
"Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit...
AlionaBujoreanu
 
ITI COPA Question Paper PDF 2017 Theory MCQ
ITI COPA Question Paper PDF 2017 Theory MCQITI COPA Question Paper PDF 2017 Theory MCQ
ITI COPA Question Paper PDF 2017 Theory MCQ
SONU HEETSON
 
How to Configure Extra Steps During Checkout in Odoo 18 Website
How to Configure Extra Steps During Checkout in Odoo 18 WebsiteHow to Configure Extra Steps During Checkout in Odoo 18 Website
How to Configure Extra Steps During Checkout in Odoo 18 Website
Celine George
 
INDIA QUIZ FOR SCHOOLS | THE QUIZ CLUB OF PSGCAS | AUGUST 2024
INDIA QUIZ FOR SCHOOLS | THE QUIZ CLUB OF PSGCAS | AUGUST 2024INDIA QUIZ FOR SCHOOLS | THE QUIZ CLUB OF PSGCAS | AUGUST 2024
INDIA QUIZ FOR SCHOOLS | THE QUIZ CLUB OF PSGCAS | AUGUST 2024
Quiz Club of PSG College of Arts & Science
 
How to Add Button in Chatter in Odoo 18 - Odoo Slides
How to Add Button in Chatter in Odoo 18 - Odoo SlidesHow to Add Button in Chatter in Odoo 18 - Odoo Slides
How to Add Button in Chatter in Odoo 18 - Odoo Slides
Celine George
 
Peer Assesment- Libby.docx..............
Peer Assesment- Libby.docx..............Peer Assesment- Libby.docx..............
Peer Assesment- Libby.docx..............
19lburrell
 
How to Manage Cross Selling in Odoo 18 Sales
How to Manage Cross Selling in Odoo 18 SalesHow to Manage Cross Selling in Odoo 18 Sales
How to Manage Cross Selling in Odoo 18 Sales
Celine George
 
PUBH1000 Slides - Module 12: Advocacy for Health
PUBH1000 Slides - Module 12: Advocacy for HealthPUBH1000 Slides - Module 12: Advocacy for Health
PUBH1000 Slides - Module 12: Advocacy for Health
JonathanHallett4
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
Aerospace Engineering Homework Help Guide – Expert Support for Academic Success
Aerospace Engineering Homework Help Guide – Expert Support for Academic SuccessAerospace Engineering Homework Help Guide – Expert Support for Academic Success
Aerospace Engineering Homework Help Guide – Expert Support for Academic Success
online college homework help
 
Module 1: Foundations of Research
Module 1: Foundations of ResearchModule 1: Foundations of Research
Module 1: Foundations of Research
drroxannekemp
 
Module_2_Types_and_Approaches_of_Research (2).pptx
Module_2_Types_and_Approaches_of_Research (2).pptxModule_2_Types_and_Approaches_of_Research (2).pptx
Module_2_Types_and_Approaches_of_Research (2).pptx
drroxannekemp
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-17-2025 .pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-17-2025  .pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-17-2025  .pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-17-2025 .pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
libbys peer assesment.docx..............
libbys peer assesment.docx..............libbys peer assesment.docx..............
libbys peer assesment.docx..............
19lburrell
 
IMPACT_OF_SOCIAL-MEDIA- AMONG- TEENAGERS
IMPACT_OF_SOCIAL-MEDIA- AMONG- TEENAGERSIMPACT_OF_SOCIAL-MEDIA- AMONG- TEENAGERS
IMPACT_OF_SOCIAL-MEDIA- AMONG- TEENAGERS
rajaselviazhagiri1
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
"Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit...
"Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit..."Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit...
"Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit...
AlionaBujoreanu
 
ITI COPA Question Paper PDF 2017 Theory MCQ
ITI COPA Question Paper PDF 2017 Theory MCQITI COPA Question Paper PDF 2017 Theory MCQ
ITI COPA Question Paper PDF 2017 Theory MCQ
SONU HEETSON
 
How to Configure Extra Steps During Checkout in Odoo 18 Website
How to Configure Extra Steps During Checkout in Odoo 18 WebsiteHow to Configure Extra Steps During Checkout in Odoo 18 Website
How to Configure Extra Steps During Checkout in Odoo 18 Website
Celine George
 
How to Add Button in Chatter in Odoo 18 - Odoo Slides
How to Add Button in Chatter in Odoo 18 - Odoo SlidesHow to Add Button in Chatter in Odoo 18 - Odoo Slides
How to Add Button in Chatter in Odoo 18 - Odoo Slides
Celine George
 
Peer Assesment- Libby.docx..............
Peer Assesment- Libby.docx..............Peer Assesment- Libby.docx..............
Peer Assesment- Libby.docx..............
19lburrell
 
How to Manage Cross Selling in Odoo 18 Sales
How to Manage Cross Selling in Odoo 18 SalesHow to Manage Cross Selling in Odoo 18 Sales
How to Manage Cross Selling in Odoo 18 Sales
Celine George
 
PUBH1000 Slides - Module 12: Advocacy for Health
PUBH1000 Slides - Module 12: Advocacy for HealthPUBH1000 Slides - Module 12: Advocacy for Health
PUBH1000 Slides - Module 12: Advocacy for Health
JonathanHallett4
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
Aerospace Engineering Homework Help Guide – Expert Support for Academic Success
Aerospace Engineering Homework Help Guide – Expert Support for Academic SuccessAerospace Engineering Homework Help Guide – Expert Support for Academic Success
Aerospace Engineering Homework Help Guide – Expert Support for Academic Success
online college homework help
 
Module 1: Foundations of Research
Module 1: Foundations of ResearchModule 1: Foundations of Research
Module 1: Foundations of Research
drroxannekemp
 
Module_2_Types_and_Approaches_of_Research (2).pptx
Module_2_Types_and_Approaches_of_Research (2).pptxModule_2_Types_and_Approaches_of_Research (2).pptx
Module_2_Types_and_Approaches_of_Research (2).pptx
drroxannekemp
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
Ad

Chp8_C++_Functions_Part2_User-defined functions.pptx

  • 2. Introduction : • A complex program is often easier to solve by dividing it into several smaller parts, each of which can be solved by itself This is called structured programming. • These parts are sometimes made into functions in C++. • All C++ programs must contain the function main( ). • The execution of the program starts from the function main( ) 2 C++ Programming, Ali Alsbou
  • 3. Advantages of Functions • Functions make programs easier to write, debug, and understand. • Functions can be called several times in the same program, allowing the code to be reused. 3 C++ Programming, Ali Alsbou
  • 4. Need to know • Functions invoked by a function–call- statement which consist of it’s name and information it needs (arguments) functionName (argument); • All other functions are directly or indirectly called from main. • The purpose of a function is to receive data, process it and return a value to the function which has called it. 4 C++ Programming, Ali Alsbou
  • 5. User-defined functions • Standard C++ Library is still not sufficient for most programming tasks. • Programmers also need to be able to define their own functions 5 C++ Programming, Ali Alsbou
  • 6. function–call Principle • Boss To Worker A Boss (the calling/caller function) asks a worker (the called function) to perform a task and return result when it is done. 6
  • 7. 7 C++ program Flow of Control The following diagram shows how the flow control of a program is changed by functions. Note: usual main( ) Calls other functions, but other functions can call each other C++ Programming, Ali Alsbou
  • 8. Function Definitions : How to write : 8 Function definition format return-value-type function-name( type parameter-list ) { declarations and statements return; } 1) Return-value-type: data type of the result (default int) void – indicates that the function returns nothing 2) Function-name: any valid identifier 3) Parameter-list: comma separated list, declares parameters A type must be listed for each parameter The function header 2 3 4 5 1 C++ Programming, Ali Alsbou Each function has its own name. Function name follows rules of naming identifiers as variables and constants
  • 9. Function definition format return-value-type function-name( type parameter-list ) { declarations and statements return; } 4) function body (block)  Variables can be defined inside blocks (can be nested)  Functions can not be defined inside other functions 5) Returning control :Function return ONLY one value If nothing returned • return; • or, until reaches right brace If something returned • return expression; 4 5
  • 10. Function return value types 10 int f1(Parameter List) { return value ; } void f2(Parameter List) { return; // nothing returned } void f2(Parameter List) { // nothing returned } If return type is missing, it means int. f2(Parameter List) { } 1 3 4 2 C++ Programming, Ali Alsbou void Function A function that is not supposed to return a value(RETURN result) has a return type of void.
  • 11. Function Parameters • The purpose is to allow passing arguments to the function from the location where it is called from. • Parameters declared in the function header within parenthesis • Either have a single, multiple parameters or have no parameters • List of a parameters are separated by commas • Each parameter must be defined as follows DataType parameterName • Note : The parameters may or may not be altered by the function. 11 char f1(int x, int y) { return value ;} C++ Programming, Ali Alsbou
  • 12. Exercises(1) • Write C++ functions that : • Find summation of two integer number(as parameters) and return result. • Find subtraction of two integer number(as parameters) and return result. • simply prints any message.
  • 14. Example (2) 14 Write a function to compute n! C++ Programming, Ali Alsbou
  • 15. General form of C++ program with functions 15 The function definition can be placed anywhere in the program after the function prototypes. C++ Programming, Ali Alsbou
  • 16. Function Prototypes(declaration) • Prototype only needed if function definition comes after use in program • Alternative to Prototype is to place function definition before main() function • Write the Function prototype after include<> statements, and before main function. • Function prototype statement is a function definition header terminated by the semicolon; • The general form of the declaration is Return_ type function_ name ( parameter_ list );  Prototype must match function definition header int square(int y); 16 C++ Programming, Ali Alsbou int square(int); Note : The variables in the function declaration can be optional but data types are necessary
  • 17. Function prototype : Con’t • Function Definition double maximum(double x,double y,double z) { … } • Function prototype double maximum(double x,double y,double z); Or double maximum(double , double , double ); 17 C++ Programming, Ali Alsbou
  • 18. Example (3) : Function Prototypes 1. double CircleArea(double radius); 2. double CircleArea(double); 3. int calculation(int n,float j); 4. int calculation (int,float); 5. int calculation (int n,float); 6. double computeTax(double income); 18 C++ Programming, Ali Alsbou
  • 19. Using Function How Function Call Works 19 Functions invoked by a function–call-statement which consist of it’s name and information it needs (arguments) functionName (argument);  Each value passed in a function call is referred to as an Argument - Arguments may be constant value ,variable or expression  Arguments passed by value and by reference (later .)  Arguments (Passed in a Function call) and parameters (defined in a function header) MUST match in: Number , Order and Data types void Display_Msg(int x) { if (x > 60) cout<<"You passed"; else cout<<“You failed"; } int main() { Display_Msg(87); return 0; } Argument Parameter C++ Programming, Ali Alsbou
  • 20. Using Function How Function Call Works – Cont. 20 C++ Programming, Ali Alsbou if function return value: int func1(int value) { result=value; return result; } Use func. Calling statement with : - Variable Ex. x= func1(3); - output statement Ex. cout<< func1(3) - Expression Ex. x=func1(3)+5- func1(4);
  • 21. Function–call-statement Example 21 C++ Programming, Ali Alsbou function–call-statement: • cout<<square (2); • cout<<square (2+6); • y=2; X= square (y); // X= 4 • if (square (y) > 2) cout <<“True”; • for( int c=0; c> square (2);c--) …..
  • 22. Function–call-statement Example • if function return nothing (void function): void func1(int value) { result=value; return; // or no need to write this } • Use func. Calling statement like: func1(3); //since this function return nothing
  • 23. Function Call Methods Passing mechanism Two ways to pass arguments to functions • Call by value • Call by reference (memory locations )  Mixed Methods Parameter lists can include pass-by-value and pass-by-reference parameters 23 C++ Programming, Ali Alsbou
  • 24. Call by value  A copy of the value is passed  a copy of the parameters value is taken from the calling function and passed to the called function  Suppose that : void exam(int b); func. Prototype a=27; exam(a); func. calling 24 All the pervious examples used this method 27 27 a b B=b++; 27 28 a b copy of a C++ Programming, Ali Alsbou
  • 25. Example (4)  a copy of the parameters value is taken from the calling function and passed to the called function
  • 27. Example(6) 1.// Creating and using a programmer-defined function. 2.#include <iostream.h> 3. int square( int ); // function prototype 4. int main( ) { 1.for ( int x = 1; x <= 10; x++ ) 2.cout << square( x ) << " "; // function call statement 3.cout << endl; 4.return 0; // indicates successful termination 5. } // end main 6.int square( int y ) // y is a copy of argument to function 7. { 8. return y * y; // returns square of y as an int 9. } // end function square 27 1 4 9 16 25 36 49 64 81 100 C++ Programming, Ali Alsbou
  • 28. Example(7) Write a program to find the average of three integer marks (use functions)? 28 #include<iostream.h> float avg(int,int,int); //function prototype main() { int m1,m2,m3; cout <<"Enter three marks :"; cin>>m1>>m2>>m3; cout <<"The average is : "<< avg(m1,m2,m3); //function calling } float avg(int a,int b , int c) //function definition { float d; d=(a+b+c)/3.0; return d; } C++ Programming, Ali Alsbou
  • 29. Example(8) #include<iostream.h> int max (int a,int b,int c); main() { int x,y,z,m; cout <<"Enter three numbers :"; cin>>x>>y>>z; m = max(x,y,z); cout <<"the maximum number is "<< m; } int max (int a,int b,int c) { int m=a; if (m<b) m=b; if (m<c) m=c; return m; } 29 #include<iostream.h> int max (int a,int b,int c) { int m=a; if (m<b) m=b; if (m<c) m=c; return m; } main() { int x,y,z,m; cout <<"Enter three numbers :"; cin>>x>>y>>z; m = max(x,y,z); cout <<"the maximum number is "<< m; } 1 2 C++ Programming, Ali Alsbou
  • 30. Example (9) Write C++ program, using function, to find the summation of the following series: 30 #include<iostream.h> int summation ( int x) { int i = 1, sum = 0; while ( i <= x ) { sum += i * i ; i++; } return (sum); } main ( ) { int n ,s; cout << "enter positive number" cin >> n; s = summation ( n ); cout << "sum is: " << s << endl; } C++ Programming, Ali Alsbou
  • 31. Example(10) void Function take no arguments If the function Does Not Take Arguments specify this with EMPTY-LIST OR write void inside #include<iostream.h> void funA(); void funB(void) main() { funA(); funB(); return 0; } void funA() { cout << "Function-A takes no arqumentsn"; } void funB() { cout << "Also Function-B takes No argumentsn"; } C++ Programming, Ali Alsbou Will be the same in all cases
  • 32. Example(11) #include <iostream.h> void even (int); main() { for( int i=20;i<35;i++) even(i); } void even (int x) { if(x %2==0) cout<<x<<" "; } 32 Print the even numbers between (20,35) using function void even (int); C++ Programming, Ali Alsbou
  • 33. Call by reference • This method is more efficient and provides higher execution speed than the call by value method, but call by value is more direct and easy to use. • gives the called function the ability to directly access the caller’s value, and to modify it. 33 C++ Programming, Ali Alsbou
  • 34. Call by reference • The argument to a reference parameter must be a variable, not a constant or an expression • "address of " actual argument is passed • The parameter in function definition must be prefixed with ampersand(&) void fname (type &);// prototype main() { fname(argument); } void fname(type &parameter_name) { … } // passing address of argument
  • 35. Example(12) #include <iostream.h> void increment (int ); int main () { int a=5; increment(a); cout<<a<<endl; return 0; } void increment (int z) 35 #include <iostream.h> void increment (int &); int main ( ) { int a=5; increment(a); cout<<a<<endl; return 0; } void increment (int &z) { z++; } Call by reference Call by value //Value a is copied to z; C++ Programming, Ali Alsbou
  • 36. Example(13) #include<iostream> int square(int); //prototype call by value function void squarref(int &); // prototype call by –reference function int main() { int x=2, z=4; cout<< "x=" <<x << " before calling squareVal"<<endl; square(x) ; // call by value cout<< "x=" <<x << " After returning"<<endl; cout<< "z=" <<z << " before calling squareRef"<<endl; squarref(z); // call by reference cout<< "z=" <<z<< " After returning squareRef"<<endl; return 0; } 36 void square(int a) { a*=a; // caller’s argument not modified } void squarref(int &cRef) { cRef *= cRef; // caller’s argument modified } C++ Programming, Ali Alsbou
  • 37. Example(14): swap Function // swap() function definition void swap(double & num1, double & num2) // swap the values of num1 and num2 { double temp; temp = num1; // Why do we need temp? num1 = num2; num2 = temp; } 37 swap(oneNum, anotherNum); C++ Programming, Ali Alsbou
  • 38. Example(15) #include<iostream.h> float rectangle(float width, int &height) { float area; // Area of the rectangle area = width * height ; return (area); } int main() { int h=3; float area=rectangle(2,h); cout<< area; return 0; } 38 C++ Programming, Ali Alsbou
  • 39. Illegal function Call Void calc(double l,double w,double & a,double & p); Suppose that : double a =3.0,b=4.0,c=5.0,d= 6.0,e=7.0; const double x = 5.0, y = 6.0; The following function calls are illegal: • calc(3.0, 4.0, 5.0, 6.0); • calc(a, b, 5.0, 6.0); • calc(a, b, c*d, e); • calc(a, b, x, y); 39 C++ Programming, Ali Alsbou
  • 40. Exercise(2) Suppose that : double circleArea(double & radius);// Pass by reference double r=2.5; Where is the errors in the following statements? area1 = circleArea(3*r+2.0);// SYNTAX ERROR! area2 = circleArea(3.5); // SYNTAX ERROR! 40 C++ Programming, Ali Alsbou
  • 41. Global vs. local variables 41 C++ Programming, Ali Alsbou
  • 42. Global vs. local variables Scope of variable : • A scope (the part of the program code that can use it) Global variables : • defined outside and before function main: • all functions can see it and using it and can be accessible and used anywhere in the entire program. (Scope) • Global variables can live as long as the program is executed 42 C++ Programming, Ali Alsbou
  • 43. Example(16) Global variables : #include <iostream.h> int x = 0; // global variable void f1( ) { x++; } void f2( ) { x+=4; f1( ); } main( ) { f2( ); cout << x << endl; } 43 C++ Programming, Ali Alsbou
  • 44. Local variables : • Local variables are declared inside the function body and exist as long as the function is running and destroyed(de-allocated) when the function exit • You have to initialize the local variable before using it • If a function defines a local variable and there was a global variable with the same name, the function uses its local variable instead of using the global variable • A local variable can be used only in the function where it is defined 44 C++ Programming, Ali Alsbou
  • 45. Example(17) #include <iostream.h> int x=99; // Global variable Void fun(); void main() { int x = 4; // loacl variable fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl;} 45 C++ Programming, Ali Alsbou
  • 46. Example(18) #include<iostream.h> int x,y; //Global Variables int add2(int, int); main() { int s; x = 11; y = 22; cout << "global x=" << x << endl; cout << "Global y=" << y << endl; s = add2(x, y); cout <<x <<"+" << y << "=" << s; cout<<endl; cout<<"n---end of output---n"; return 0; } 46 int add2(int x1,int y1) { int x; //local variables x=44; cout << "nLocal x=" << x << endl; return x1+y1; } C++ Programming, Ali Alsbou
  • 47. Example(19) #include<iostream.h> void f(void); main ( ) { f(); f(); f(); } void f(void) { int x=0; x++; cout<<x<<endl; } 47 C++ Programming, Ali Alsbou
  • 48. Static vs. Automatic variables • Normal” local variables go out of scope and are de- allocated when a function terminates. • Static variables remain and retain their value. • Format: • When declare static variable it initializes to 0 unless you specify another value 48 void f( ) { static <variable_type> <variable_name> … } C++ Programming, Ali Alsbou
  • 49. Example(21) void my_function ( ) { int count = 1; cout<<"this function has been called "<<count<<"n"; count++; return; } int main(){ my_function(); my_function(); my_function(); return 0; } 49 C++ Programming, Ali Alsbou
  • 50. Example(21)- Cont. void my_function ( ) { static int count = 1; cout<<"this function has been called "<<count<<"n"; count++; return; } int main(){ my_function(); my_function(); my_function(); return 0;} 50 C++ Programming, Ali Alsbou
  • 51. Example(22) #include <iostream> void showstat( int curr ) { static int nStatic; nStatic += curr; cout << "nStatic is " << nStatic << endl; } int main() { for ( int i = 0; i < 4; i++ ) showstat( i ); } 51 nStatic is 0 nStatic is 1 nStatic is 3 nStatic is 6 C++ Programming, Ali Alsbou
  • 53. Passing Arrays to Functions • To pass an array argument to a function Specify array name without brackets Array a is declared as int a[ 24 ]; The function call modifyArray( a, 24 ); passes array a and its size to function modifyArray • Array size is normally passed as another argument so the function can process the specific number of elements in the array • Arrays are passed by reference (Function call actually passes starting address of array ) 53 C++ Programming, Ali Alsbou
  • 54. Passing Arrays to Functions (Cont.) • Individual array elements passed by value Use the subscripted name of the array element as an argument Example: modifyElement( a[ 3 ] ); void modifyElement( int e ) { cout << "Value of element in modifyElement: " << ( e *= 2 ) << endl; } 54 Function Calling Function definision C++ Programming, Ali Alsbou
  • 55. Functions that take arrays as arguments • Function definition Example: void modArray( int b[], int arraySize ); • Array parameter may include the size of the array • Compiler will ignore it, though Compiler only cares about the address of the first element 55 C++ Programming, Ali Alsbou
  • 56. Exercise(3) Using function, write a program to read array items then print them 56 #include<iostream.h> void read (int [],int); void print(int [],int); main() { int R[5]; read (R,5); print(R,5); } void print (int F[],int x) { int i; for(i=0;i<x;i++) cout<<F[i]<<" "; } void read (int M[],int n) { int i; for(i=0;i<n;i++) { cout <<"Enter item number "<<i<<" : "; cin>> M[i]; } } C++ Programming, Ali Alsbou
  • 57. Passing 2D-array to function you must determine the size of column in two dimension array 57 C++ Programming, Ali Alsbou
  • 58. Example(23) #include<iostream.h> void printArray (int [][3]) ; int main ( ) { int array1[2][3]={{1,2,3},{4,5,6}}; cout<<"Array1="; printarray(array1); } void printarray (int a[][3]) { for (int i=0 ; i<2 ; i++) { for (int j=0 ; j<3 ; j++) cout<<a[i][j]; cout<<endl; } } 58 C++ Programming, Ali Alsbou
  • 59. Recursive Function ( Recursion) : A function that calls itself A recursive function has two parts: 1) the terminal/base case. a stopping condition 2) the reducing case/recursive step an expression of the computation or definition in terms of itself Every recursive call reduces the original problem, bringing it increasingly closer to a base case until it becomes that case. 59 C++ Programming, Ali Alsbou
  • 60. General algorithm for recursion 60 if (terminal_condition) terminal_case else reducing_case if (!terminal_condition) reducing_case C++ Programming, Ali Alsbou
  • 61. Example(24): print numbers counting down # include<iostream> void print(int n) { if (n==0) return; cout<<n<<endl; print(n-1); } 61 int print2(int n) { if (n==0) return 1; cout<<n<<endl; return print2(n-1); } C++ Programming, Ali Alsbou main( ) { int n; cin>>n; print(n); cout<<print2(n); }
  • 62. Factorials by recursion • Easy way to calculate n! • n! = 1 if n == 1 or n==0 • Otherwise, n! = n * (n-1)! 62 C++ Programming, Ali Alsbou
  • 63. Example(25): Factorials by recursion – Cont. #include<iostream.h> int factorial (int n); main ( ) { int n; cin>>n; cout<<factorial(n); } int factorial (int n) { if (n==1 || n==0) // base case return 1; else return n * factorial(n-1); // recursive part } 63 recursive step terminal_case C++ Programming, Ali Alsbou
  • 64. Recursive function Find X to the power n • Terminal case if n==0 since x to powr 0 is =1 • Recursive case x * power(x,n-1) 64 C++ Programming, Ali Alsbou
  • 65. Example(26) 65 C++ Programming, Ali Alsbou #include<iostream.h> int power (int x , int n ); main ( ) { int x,y; cout<<"enter two numbern"; cin>>x>>y; cout<<power(x,y);} int power (int x, int n ) { if (n==0) return 1; // base case else return x* power(x,n-1); // recursive part }
  • 66. Example(27): 66 C++ Programming, Ali Alsbou Write a recursive function to find the sum of the first 4 elements of an integer array "a[ ]".
  • 68. Note about recursion function • Infinite recursion Any recursive function that not bringing it to a base case 68 C++ Programming, Ali Alsbou

Editor's Notes

  • #2: البرمجة المهيكلة
  • #4: The purpose of a function is to receive data, process it and return a value to the function which has called it. The terms calling function and called function are derived from the telephone communication.
  • #12: int subtraction (int a, int b) { int r; r=a-b; return r; } int addition (int a, int b) { int r; r=a+b; return r; }
  • #13: float triangle(float width, float height) { float area; area = width * height / 2.0; return (area); }
  • #21: float triangle(float width, float height) { float area; area = width * height / 2.0; return (area); }
  • #26: #include<iostream.h> float mult (int x, int y,float); // int mult (int , int ); int add (int x, int y) { int sum; sum=x+y; return sum; // or return x+y ; } int main () { int result; float k; result = add (3,2); cout << "1. The result is " << result<<endl; k= mult(2,3,4.52); cout << "2. The result is " <<k; } float mult(int x, int y,float a) { return x*y*a ; }
  • #59: Every recursive function must have a base case or a stopping condition
  • #66: #include<iostream.h> int sum (int a[],int n) { if (n==1) return a[0]; // base case else return (a[n-1] + sum(a,n-1)); } int main ( ) { int a[10],i; for(i=0;i<4;i++) cin>>a[i]; cout<< "sum = " << sum (a,4); return 0; }
  • #67: #include<iostream.h> int calc ( int n ) { if (n <=1) return n; else return calc ( n - 1 ) + n ; } int main () { cout<< calc(4) <<endl; }
  翻译: