SlideShare a Scribd company logo
Chapter Four
Functions in C++
1
• Function - a subprogram that can act on data and return
a value
• Every C++ program has at least one function, main(),
where program execution begins
• A C++ program might contain more than one function.
• Functions may interact using function call
• Functions in C++ come in two varieties:
– user-defined
– built-in
2
3
Predefined Functions (continued)
• Some of the predefined mathematical functions are:
sqrt(x)
pow(x,y)
floor(x)
• Predefined functions are organized into separate
libraries
• I/O functions are in iostream header
• Math functions are in cmath header
4
The Power Function (pow)
• pow(x,y) calculates xy, pow(2,3) = 8.0
• pow returns a value of type double
• x and y are called the parameters (or
arguments) of the function pow
• Function pow has two parameters
5
The sqrt and floor Functions
• The square root function sqrt(x)
– Calculates the non-negative square root of x, for
x >= 0.0
– sqrt(2.25) is 1.5
– Type double
– Has only one parameter
6
The sqrt and floor Functions
(continued)
• The floor function floor(x)
– Calculates largest whole number not greater than
x
– floor(48.79) is 48.0
– Type double
– Has only one parameter
Declaration of Functions
• Functions must be declared before use
• The declaration tells the compiler
– The name,
– Return type,
– Parameters of the function
• Three ways
– Write your prototype into a file, and then use the #include
directive to include it in your program.
– Write the prototype into the file in which your function is
used.
– Define the function before it is called by any other function.
9
Function Prototypes
• The declaration of a function is called its prototype
• Is a statement - it ends with a semicolon
• It consists of the function's
– return type,
– name,
– parameter list
• Syntax
– return_type function_name (type
[parameterName1], type [ParameterName2] ... );
• E.g. long Area(int, int);
Or
long Area(int length, int width);
10
Function Prototypes
• All functions have a return type
• If the function doesn’t have a return type void will be used
– void is a reserved word
• The function prototype usually placed at the beginning of the
program
• The definition of the prototype must be given
• Many of the built-in functions have their function prototypes already
written in the header files you include in your program by using
#include
11
Defining a Function
• The definition tells the compiler how the function works.
• Consists of :
– the function header :
• like the function prototype except that the parameters must be
named
• there is no terminating semicolon
– its body
• the task of the function
• Syntax
return_type function_name(parameter declarations)
{
declarations;
statements;
}
12
Defining a Function
• E.g.
long Area(long l, long w)
{
return l * w;
}
• The return statement without any value is typically used
to exit the function early
• C++ does not allow nested functions
– The definition of one function cannot be included in
the body of another function
• A function definition must agree in return type and
parameter list with its prototype
13
// Creating and using a programmer-defined function.
#include <iostream.h>
int square( int ); // function prototype
int main()
{
// loop 10 times and calculate and output
// square of x each time
for ( int x = 1; x <= 10; x++ )
cout << square( x ) << " "; // function call
cout << endl;
return 0; // indicates successful termination
} // end main
// square function definition returns square of an integer
int square( int y ) // y is a copy of argument to function
{
return y * y; // returns square of y as an int
} // end function square
Definition of square. y is a
copy of the argument passed.
Returns y * y, or y squared.
Function prototype: specifies data types
of arguments and return values.
square expects an int, and returns
an int.
Parentheses () cause function to be called.
When done, it returns the result.
1 4 9 16 25 36 49 64 81 100
14
Program Using a Function
#include <iostream.h>
double Celsius_to_Fahr(double); //Function Prototype
int main()
{
double temp,result;
cout<<“enter the temperature”<<endl;
cin>>temp;
result= Celsius_to_Fahr(temp);
cout<<“the corresponding Fahrenheit is”<<result<<
endl;
return 0;
}
double Celsius_to_Fahr(double Celsius)
{
double temp; // Declare variables
temp = (9.0/5.0)*Celsius + 32; // Convert
return temp;
}
15
Scope of identifier
• Refers to where in the program an identifier is accessible
• Determines how long it is available to your program and
where it can be accessed
• Two kind
– Local identifier - identifiers declared within a function
(or block)
– Global identifier – identifiers declared outside of every
function definition
16
Local scope
• You can declare variables within the body of the function
– local variables
– When the function returns, the local variables are no
longer available
• Variables declared within a block are scoped to that
block – Local to that block
– they can be accessed only within that block and "go
out of existence" when that block ends
– E.g.
for (int i = 0;i<5; i++)
cout<<i;
i=+10; // compilation error i is inaccessible
17
Global Scope
• Variables defined outside of any function have global
scope
• Available for any function in the program, including main()
• A local variable with the same name as a global
variable hides the global variable - when used within
the function
18
#include <iostream.h>
void myFunction(); //
prototype
int x = 5, y = 7; //
global variables
int main()
{
cout << "x from main: "
<< x << "n";
cout << "y from main: "
<< y << "nn";
myFunction();
cout << "Back from
myFunction!nn";
cout << "x from main: "
<< x << "n";
cout << "y from main: "
<< y << "n";
return 0;
}
void myFunction()
{
int y = 10;
cout << "x from myFunction:
" << x << "n";
cout << "y from myFunction:
" << y << "nn";
}
Output:
x from main: 5
y from main: 7
x from myFunction: 5
y from myFunction: 10
Back from myFunction!
x from main: 5
y from main: 7
19
Unary Scope Resolution Operator ::
• Using ::, one can access an global variable even
if it is over-shadowed by a local variable of the
same name.
• E.g.
#include <iostream.h>
float num=10.8;
int main()
{
float num= 9.66;
cout<<“the value of num is:”<<::num<<endl;
return 0;
}
20
inline Functions
• Function calls
– Cause execution-time overhead
• Qualifier inline before function return type
"advises" a function to be inlined
• Puts copy of function's code in place of function call
– Speeds up performance but increases file size
– Compiler can ignore the inline qualifier
• Ignores all but the smallest functions
– E.g.
inline double cube( const double s )
{
return s * s * s;
} 21
inline functions
• Advantage: function call overhead is eliminated,
thus faster and less memory consuming
• Disadvantage: the code is expanded during
compilation so that executable file is large
22
Functions with Default Parameters
• When a function is called
– The number of actual and formal parameters must be
the same
• C++ relaxes this condition for functions with default
parameters
• You specify the value of a default parameter when the
function name appears for the first time, such as in the
prototype
23
# include<iostream>
Using namespace std;
int product (int x, int y=3)
{
int multiply;
multiply = x* y;
return multiply;
}
void main()
{
// First call to function ‘product’
cout<<product(10)<<endl;
// Second call to function ‘product’
cout<<product(20,12);
}
24
Empty Parameter Lists
• functions can take no arguments
• To declare that a function takes no parameters:
– Write void or nothing in parentheses
• E.g
– void print1( void );
– void print2();
25
Parameter Passing
• Call by Value
– Value of the function argument passed to the
formal parameter of the function
– Copy of data passed to function
– Changes to copy do not change original
• Call by Reference
– Address of the function argument passed to the
formal parameter of the function
26
Call by Reference
• If a formal parameter is a reference parameter
– It receives the address of the corresponding actual parameter
– A reference parameter stores the address of the corresponding
actual parameter
• During program execution to manipulate the data
– The address stored in the reference parameter directs it to the
memory space of the corresponding actual parameter
– A reference parameter receives the address of the actual
parameter
• Reference parameters can:
– Pass one or more values from a function
– Change the value of the actual parameter
27
Call by Reference
• Reference parameters are useful in three
situations:
– Returning more than one value
– Changing the actual parameter
– When passing the address would save
memory space and time
28
29
Reference Variable Example
int count;
int &x = count;
// Create x as an alias for count
count = 1;
cout << “x is “ << x << endl;
x++;
cout << “count is “ << count << endl;
// Initializing and using a reference.
#include <iostream>
using namespace std;
int main()
{
int x = 3;
int &y = x; // y refers to (is an alias for) x
cout << "x = " << x << endl << "y = " << y << endl;
y = 7; // actually modifies x
cout << "x = " << x << endl << "y = " << y << endl;
return 0;
} // end main
30
Call by Value Example
/* Incorrect function to switch two values */
void swap(int a, int b)
{
int hold;
hold = a;
a = b;
b = hold;
return;
}
31
int a = 3, b = 5;
Swap( a,b);
Cout<<a<<b;
Call by Reference Example
/* Correct function to switch two values */
void swap2(int& a, int& b)
{
int hold;
hold = a;
a = b;
b = hold;
return;
}
32
33
Recursion
• Functions can call themselves! This is
called recursion.
• Recursion is very useful – it’s often very
simple to express a complicated
computation recursively.
Finding Factorial Recursively
5!
5*4!
4*3!
3*2!
2*1!
1
5!
5*4!
4*3!
3*2!
2*1!
1
Final value=120
1
2!=2*1=2 returned
3!=3*2=6 returned
4!=4*6=24 returned
5!=5*24=120 returned
34
Finding Factorial iteratively
#include<iostream.h>
unsigned long factorial(unsigned long);//prototype
int main()
{
int num;
cout<<"enter a positive integer:";
cin>>num;
cout<<"The factorial of "<<num<<" is:
"<<factorial(num)<<endl;
return 0;
}
unsigned long factorial(unsigned long n)
{
unsigned long fact = 1;
for( int i=1; i<=n; i++)
fact*=i;
return fact;
}
35
//Recursive factorial Function
#include<iostream.h>
unsigned long factorial(unsigned long);//prototype
int main()
{
int num;
cout<<“enter a positive integer:”;
cin>>num;
cout<<“factorial=“<<factorial(num);
return 0;
}
unsigned long factorial(unsigned long n)
{
if ( n <= 1) //the base case
return 1;
else
return n * factorial (n - 1);
}
Finding Factorial Recursively
36
37
Designing Recursive Functions
• Define “Base Case”:
– The situation in which the function does not
call itself.
• Define “recursive step”:
– Compute the return value the help of the
function itself.
38
Recursion Base Case
• The base case corresponds to a case in which you know
the answer (the function returns the value immediately),
or can easily compute the answer.
• If you don’t have a base case you can’t use recursion!
(and you probably don’t understand the problem).
39
Recursive Step
• Use the recursive call to solve a sub-
problem.
– The parameters must be different (or the
recursive call will get us no closer to the
solution).
– You generally need to do something besides
just making the recursive call.
40
Recursion is a favorite test topic
• Write a recursive C++ function that
computes the area of an nxn square.
n
n
Base case:
n=1 area=1
Recursive Step:
area = n+n-1+area(n-1)
41
Recursive area function
int area( int n) {
if (n == 1)
return(1);
else
return( n + n - 1 + area(n-1) );
}
42
Recursion Exercise
• Write a function that prints a triangle:
triangle(4); triangle(5);
* *
*** ***
***** *****
******* *******
*********
• Function overloading
– Functions with same name and different
parameters
– Should perform similar tasks
• I.e., function to square ints and function to square floats
int square( int x) {return x * x;}
float square(float x) { return x * x; }
• A call-time c++ complier selects the proper function by
examining the number, type and order of the parameters
Function Overloading
43
// overloaded function
#include <iostream>
using namespace std;
int operate (int a, int b)
{
return (a*b);
}
float operate (float a, float b)
{
return (a/b);
}
int main ()
{
int x=5,y=2;
float n=5.0,m=2.0;
cout << operate (x,y);
cout << "n";
cout << operate (n,m);
cout << "n";
return 0;
}
44

More Related Content

What's hot

Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
Function C++
Function C++ Function C++
Function C++
Shahzad Afridi
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
Sachin Yadav
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Mohammed Sikander
 
C++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIAC++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIA
Dheeraj Kataria
 
C++ functions
C++ functionsC++ functions
C++ functions
Dawood Jutt
 
functions of C++
functions of C++functions of C++
functions of C++
tarandeep_kaur
 
C++ Functions
C++ FunctionsC++ Functions
C++ Functions
sathish sak
 
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
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Nikhil Pandit
 
C++ Pointers
C++ PointersC++ Pointers
C++ Pointers
Chaand Sheikh
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
03062679929
 
Function
FunctionFunction
Function
yash patel
 
C++ functions
C++ functionsC++ functions
C++ functions
Mayank Jain
 
C++ Function
C++ FunctionC++ Function
C++ Function
PingLun Liao
 
Lecture#8 introduction to array with examples c++
Lecture#8 introduction to array with examples c++Lecture#8 introduction to array with examples c++
Lecture#8 introduction to array with examples c++
NUST Stuff
 
Lecture#9 Arrays in c++
Lecture#9 Arrays in c++Lecture#9 Arrays in c++
Lecture#9 Arrays in c++
NUST Stuff
 

What's hot (18)

Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Function C++
Function C++ Function C++
Function C++
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
C++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIAC++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIA
 
C++ functions
C++ functionsC++ functions
C++ functions
 
functions of C++
functions of C++functions of C++
functions of C++
 
C++ Functions
C++ FunctionsC++ Functions
C++ Functions
 
Learning C++ - Functions in C++ 3
Learning C++ - Functions  in C++ 3Learning C++ - Functions  in C++ 3
Learning C++ - Functions in C++ 3
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
C++ Pointers
C++ PointersC++ Pointers
C++ Pointers
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Function
FunctionFunction
Function
 
C++ functions
C++ functionsC++ functions
C++ functions
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
Lecture#8 introduction to array with examples c++
Lecture#8 introduction to array with examples c++Lecture#8 introduction to array with examples c++
Lecture#8 introduction to array with examples c++
 
Lecture#9 Arrays in c++
Lecture#9 Arrays in c++Lecture#9 Arrays in c++
Lecture#9 Arrays in c++
 

Similar to Chapter 4

C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
WaheedAnwar20
 
Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Abdul Samee
 
Functions
FunctionsFunctions
Chap 5 c++
Chap 5 c++Chap 5 c++
Review functions
Review functionsReview functions
Review functions
Kgr Sushmitha
 
Chap 5 c++
Chap 5 c++Chap 5 c++
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
GebruGetachew2
 
Functions in C++ programming language.pptx
Functions in  C++ programming language.pptxFunctions in  C++ programming language.pptx
Functions in C++ programming language.pptx
rebin5725
 
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
 
Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functionsTAlha MAlik
 
Functions in C++.pdf
Functions in C++.pdfFunctions in C++.pdf
Functions in C++.pdf
LadallaRajKumar
 
C++ Language
C++ LanguageC++ Language
C++ Language
Syed Zaid Irshad
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
TeshaleSiyum
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
TeshaleSiyum
 
eee2-day4-structures engineering college
eee2-day4-structures engineering collegeeee2-day4-structures engineering college
eee2-day4-structures engineering college
2017eee0459
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
Koteswari Kasireddy
 
4th unit full
4th unit full4th unit full
4th unit full
Murali Saktheeswaran
 

Similar to Chapter 4 (20)

C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01
 
Functions
FunctionsFunctions
Functions
 
Function
FunctionFunction
Function
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Review functions
Review functionsReview functions
Review functions
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
 
Fp201 unit5 1
Fp201 unit5 1Fp201 unit5 1
Fp201 unit5 1
 
Functions in C++ programming language.pptx
Functions in  C++ programming language.pptxFunctions in  C++ programming language.pptx
Functions in C++ programming language.pptx
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
 
Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functions
 
Functions in C++.pdf
Functions in C++.pdfFunctions in C++.pdf
Functions in C++.pdf
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
 
eee2-day4-structures engineering college
eee2-day4-structures engineering collegeeee2-day4-structures engineering college
eee2-day4-structures engineering college
 
functions
functionsfunctions
functions
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 
4th unit full
4th unit full4th unit full
4th unit full
 

More from temkin abdlkader

Steel and effect of alloying elements
Steel and effect of alloying elementsSteel and effect of alloying elements
Steel and effect of alloying elements
temkin abdlkader
 
Production of iron and steel
Production of iron and steelProduction of iron and steel
Production of iron and steel
temkin abdlkader
 
Power piont ch2 phase-transformation-in-metals (1)
Power piont   ch2 phase-transformation-in-metals (1)Power piont   ch2 phase-transformation-in-metals (1)
Power piont ch2 phase-transformation-in-metals (1)
temkin abdlkader
 
Phase transformation
Phase transformationPhase transformation
Phase transformation
temkin abdlkader
 
Ironcarbondia
IroncarbondiaIroncarbondia
Ironcarbondia
temkin abdlkader
 
Heat treatment
Heat treatmentHeat treatment
Heat treatment
temkin abdlkader
 
iron carbon phase diagram
iron carbon  phase diagramiron carbon  phase diagram
iron carbon phase diagram
temkin abdlkader
 
Cast irons
Cast  ironsCast  irons
Cast irons
temkin abdlkader
 
Dd3.15 thru-3.21-advanced-functions
Dd3.15 thru-3.21-advanced-functionsDd3.15 thru-3.21-advanced-functions
Dd3.15 thru-3.21-advanced-functionstemkin abdlkader
 
Intro logic ch 4 categorical syllogism
Intro logic ch 4 categorical syllogismIntro logic ch 4 categorical syllogism
Intro logic ch 4 categorical syllogismtemkin abdlkader
 
Intro logic ch 4 categorical propositions
Intro logic ch 4 categorical propositionsIntro logic ch 4 categorical propositions
Intro logic ch 4 categorical propositionstemkin abdlkader
 

More from temkin abdlkader (20)

Steel and effect of alloying elements
Steel and effect of alloying elementsSteel and effect of alloying elements
Steel and effect of alloying elements
 
Production of iron and steel
Production of iron and steelProduction of iron and steel
Production of iron and steel
 
Power piont ch2 phase-transformation-in-metals (1)
Power piont   ch2 phase-transformation-in-metals (1)Power piont   ch2 phase-transformation-in-metals (1)
Power piont ch2 phase-transformation-in-metals (1)
 
Phase transformation
Phase transformationPhase transformation
Phase transformation
 
Ironcarbondia
IroncarbondiaIroncarbondia
Ironcarbondia
 
Heat treatment
Heat treatmentHeat treatment
Heat treatment
 
iron carbon phase diagram
iron carbon  phase diagramiron carbon  phase diagram
iron carbon phase diagram
 
Cast irons
Cast  ironsCast  irons
Cast irons
 
Workshop1
Workshop1Workshop1
Workshop1
 
Intro to c++
Intro to c++Intro to c++
Intro to c++
 
Dd3.15 thru-3.21-advanced-functions
Dd3.15 thru-3.21-advanced-functionsDd3.15 thru-3.21-advanced-functions
Dd3.15 thru-3.21-advanced-functions
 
04 bits andarithmetic
04 bits andarithmetic04 bits andarithmetic
04 bits andarithmetic
 
Intro logic ch 4 categorical syllogism
Intro logic ch 4 categorical syllogismIntro logic ch 4 categorical syllogism
Intro logic ch 4 categorical syllogism
 
Intro logic ch 3 doc
Intro logic ch 3 docIntro logic ch 3 doc
Intro logic ch 3 doc
 
Intro logic chaps 6 and 7
Intro logic chaps 6 and 7Intro logic chaps 6 and 7
Intro logic chaps 6 and 7
 
Intro logic ch 4 categorical propositions
Intro logic ch 4 categorical propositionsIntro logic ch 4 categorical propositions
Intro logic ch 4 categorical propositions
 
Paragraph
ParagraphParagraph
Paragraph
 
Essay
Essay Essay
Essay
 
Intro logic ch 2
Intro logic ch 2Intro logic ch 2
Intro logic ch 2
 
Intro logicnote ch 1
Intro logicnote ch 1Intro logicnote ch 1
Intro logicnote ch 1
 

Recently uploaded

Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Vladimir Iglovikov, Ph.D.
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 

Recently uploaded (20)

Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 

Chapter 4

  • 2. • Function - a subprogram that can act on data and return a value • Every C++ program has at least one function, main(), where program execution begins • A C++ program might contain more than one function. • Functions may interact using function call • Functions in C++ come in two varieties: – user-defined – built-in 2
  • 3. 3 Predefined Functions (continued) • Some of the predefined mathematical functions are: sqrt(x) pow(x,y) floor(x) • Predefined functions are organized into separate libraries • I/O functions are in iostream header • Math functions are in cmath header
  • 4. 4 The Power Function (pow) • pow(x,y) calculates xy, pow(2,3) = 8.0 • pow returns a value of type double • x and y are called the parameters (or arguments) of the function pow • Function pow has two parameters
  • 5. 5 The sqrt and floor Functions • The square root function sqrt(x) – Calculates the non-negative square root of x, for x >= 0.0 – sqrt(2.25) is 1.5 – Type double – Has only one parameter
  • 6. 6 The sqrt and floor Functions (continued) • The floor function floor(x) – Calculates largest whole number not greater than x – floor(48.79) is 48.0 – Type double – Has only one parameter
  • 7.
  • 8.
  • 9. Declaration of Functions • Functions must be declared before use • The declaration tells the compiler – The name, – Return type, – Parameters of the function • Three ways – Write your prototype into a file, and then use the #include directive to include it in your program. – Write the prototype into the file in which your function is used. – Define the function before it is called by any other function. 9
  • 10. Function Prototypes • The declaration of a function is called its prototype • Is a statement - it ends with a semicolon • It consists of the function's – return type, – name, – parameter list • Syntax – return_type function_name (type [parameterName1], type [ParameterName2] ... ); • E.g. long Area(int, int); Or long Area(int length, int width); 10
  • 11. Function Prototypes • All functions have a return type • If the function doesn’t have a return type void will be used – void is a reserved word • The function prototype usually placed at the beginning of the program • The definition of the prototype must be given • Many of the built-in functions have their function prototypes already written in the header files you include in your program by using #include 11
  • 12. Defining a Function • The definition tells the compiler how the function works. • Consists of : – the function header : • like the function prototype except that the parameters must be named • there is no terminating semicolon – its body • the task of the function • Syntax return_type function_name(parameter declarations) { declarations; statements; } 12
  • 13. Defining a Function • E.g. long Area(long l, long w) { return l * w; } • The return statement without any value is typically used to exit the function early • C++ does not allow nested functions – The definition of one function cannot be included in the body of another function • A function definition must agree in return type and parameter list with its prototype 13
  • 14. // Creating and using a programmer-defined function. #include <iostream.h> int square( int ); // function prototype int main() { // loop 10 times and calculate and output // square of x each time for ( int x = 1; x <= 10; x++ ) cout << square( x ) << " "; // function call cout << endl; return 0; // indicates successful termination } // end main // square function definition returns square of an integer int square( int y ) // y is a copy of argument to function { return y * y; // returns square of y as an int } // end function square Definition of square. y is a copy of the argument passed. Returns y * y, or y squared. Function prototype: specifies data types of arguments and return values. square expects an int, and returns an int. Parentheses () cause function to be called. When done, it returns the result. 1 4 9 16 25 36 49 64 81 100 14
  • 15. Program Using a Function #include <iostream.h> double Celsius_to_Fahr(double); //Function Prototype int main() { double temp,result; cout<<“enter the temperature”<<endl; cin>>temp; result= Celsius_to_Fahr(temp); cout<<“the corresponding Fahrenheit is”<<result<< endl; return 0; } double Celsius_to_Fahr(double Celsius) { double temp; // Declare variables temp = (9.0/5.0)*Celsius + 32; // Convert return temp; } 15
  • 16. Scope of identifier • Refers to where in the program an identifier is accessible • Determines how long it is available to your program and where it can be accessed • Two kind – Local identifier - identifiers declared within a function (or block) – Global identifier – identifiers declared outside of every function definition 16
  • 17. Local scope • You can declare variables within the body of the function – local variables – When the function returns, the local variables are no longer available • Variables declared within a block are scoped to that block – Local to that block – they can be accessed only within that block and "go out of existence" when that block ends – E.g. for (int i = 0;i<5; i++) cout<<i; i=+10; // compilation error i is inaccessible 17
  • 18. Global Scope • Variables defined outside of any function have global scope • Available for any function in the program, including main() • A local variable with the same name as a global variable hides the global variable - when used within the function 18
  • 19. #include <iostream.h> void myFunction(); // prototype int x = 5, y = 7; // global variables int main() { cout << "x from main: " << x << "n"; cout << "y from main: " << y << "nn"; myFunction(); cout << "Back from myFunction!nn"; cout << "x from main: " << x << "n"; cout << "y from main: " << y << "n"; return 0; } void myFunction() { int y = 10; cout << "x from myFunction: " << x << "n"; cout << "y from myFunction: " << y << "nn"; } Output: x from main: 5 y from main: 7 x from myFunction: 5 y from myFunction: 10 Back from myFunction! x from main: 5 y from main: 7 19
  • 20. Unary Scope Resolution Operator :: • Using ::, one can access an global variable even if it is over-shadowed by a local variable of the same name. • E.g. #include <iostream.h> float num=10.8; int main() { float num= 9.66; cout<<“the value of num is:”<<::num<<endl; return 0; } 20
  • 21. inline Functions • Function calls – Cause execution-time overhead • Qualifier inline before function return type "advises" a function to be inlined • Puts copy of function's code in place of function call – Speeds up performance but increases file size – Compiler can ignore the inline qualifier • Ignores all but the smallest functions – E.g. inline double cube( const double s ) { return s * s * s; } 21
  • 22. inline functions • Advantage: function call overhead is eliminated, thus faster and less memory consuming • Disadvantage: the code is expanded during compilation so that executable file is large 22
  • 23. Functions with Default Parameters • When a function is called – The number of actual and formal parameters must be the same • C++ relaxes this condition for functions with default parameters • You specify the value of a default parameter when the function name appears for the first time, such as in the prototype 23
  • 24. # include<iostream> Using namespace std; int product (int x, int y=3) { int multiply; multiply = x* y; return multiply; } void main() { // First call to function ‘product’ cout<<product(10)<<endl; // Second call to function ‘product’ cout<<product(20,12); } 24
  • 25. Empty Parameter Lists • functions can take no arguments • To declare that a function takes no parameters: – Write void or nothing in parentheses • E.g – void print1( void ); – void print2(); 25
  • 26. Parameter Passing • Call by Value – Value of the function argument passed to the formal parameter of the function – Copy of data passed to function – Changes to copy do not change original • Call by Reference – Address of the function argument passed to the formal parameter of the function 26
  • 27. Call by Reference • If a formal parameter is a reference parameter – It receives the address of the corresponding actual parameter – A reference parameter stores the address of the corresponding actual parameter • During program execution to manipulate the data – The address stored in the reference parameter directs it to the memory space of the corresponding actual parameter – A reference parameter receives the address of the actual parameter • Reference parameters can: – Pass one or more values from a function – Change the value of the actual parameter 27
  • 28. Call by Reference • Reference parameters are useful in three situations: – Returning more than one value – Changing the actual parameter – When passing the address would save memory space and time 28
  • 29. 29 Reference Variable Example int count; int &x = count; // Create x as an alias for count count = 1; cout << “x is “ << x << endl; x++; cout << “count is “ << count << endl;
  • 30. // Initializing and using a reference. #include <iostream> using namespace std; int main() { int x = 3; int &y = x; // y refers to (is an alias for) x cout << "x = " << x << endl << "y = " << y << endl; y = 7; // actually modifies x cout << "x = " << x << endl << "y = " << y << endl; return 0; } // end main 30
  • 31. Call by Value Example /* Incorrect function to switch two values */ void swap(int a, int b) { int hold; hold = a; a = b; b = hold; return; } 31 int a = 3, b = 5; Swap( a,b); Cout<<a<<b;
  • 32. Call by Reference Example /* Correct function to switch two values */ void swap2(int& a, int& b) { int hold; hold = a; a = b; b = hold; return; } 32
  • 33. 33 Recursion • Functions can call themselves! This is called recursion. • Recursion is very useful – it’s often very simple to express a complicated computation recursively.
  • 34. Finding Factorial Recursively 5! 5*4! 4*3! 3*2! 2*1! 1 5! 5*4! 4*3! 3*2! 2*1! 1 Final value=120 1 2!=2*1=2 returned 3!=3*2=6 returned 4!=4*6=24 returned 5!=5*24=120 returned 34
  • 35. Finding Factorial iteratively #include<iostream.h> unsigned long factorial(unsigned long);//prototype int main() { int num; cout<<"enter a positive integer:"; cin>>num; cout<<"The factorial of "<<num<<" is: "<<factorial(num)<<endl; return 0; } unsigned long factorial(unsigned long n) { unsigned long fact = 1; for( int i=1; i<=n; i++) fact*=i; return fact; } 35
  • 36. //Recursive factorial Function #include<iostream.h> unsigned long factorial(unsigned long);//prototype int main() { int num; cout<<“enter a positive integer:”; cin>>num; cout<<“factorial=“<<factorial(num); return 0; } unsigned long factorial(unsigned long n) { if ( n <= 1) //the base case return 1; else return n * factorial (n - 1); } Finding Factorial Recursively 36
  • 37. 37 Designing Recursive Functions • Define “Base Case”: – The situation in which the function does not call itself. • Define “recursive step”: – Compute the return value the help of the function itself.
  • 38. 38 Recursion Base Case • The base case corresponds to a case in which you know the answer (the function returns the value immediately), or can easily compute the answer. • If you don’t have a base case you can’t use recursion! (and you probably don’t understand the problem).
  • 39. 39 Recursive Step • Use the recursive call to solve a sub- problem. – The parameters must be different (or the recursive call will get us no closer to the solution). – You generally need to do something besides just making the recursive call.
  • 40. 40 Recursion is a favorite test topic • Write a recursive C++ function that computes the area of an nxn square. n n Base case: n=1 area=1 Recursive Step: area = n+n-1+area(n-1)
  • 41. 41 Recursive area function int area( int n) { if (n == 1) return(1); else return( n + n - 1 + area(n-1) ); }
  • 42. 42 Recursion Exercise • Write a function that prints a triangle: triangle(4); triangle(5); * * *** *** ***** ***** ******* ******* *********
  • 43. • Function overloading – Functions with same name and different parameters – Should perform similar tasks • I.e., function to square ints and function to square floats int square( int x) {return x * x;} float square(float x) { return x * x; } • A call-time c++ complier selects the proper function by examining the number, type and order of the parameters Function Overloading 43
  • 44. // overloaded function #include <iostream> using namespace std; int operate (int a, int b) { return (a*b); } float operate (float a, float b) { return (a/b); } int main () { int x=5,y=2; float n=5.0,m=2.0; cout << operate (x,y); cout << "n"; cout << operate (n,m); cout << "n"; return 0; } 44