SlideShare ist ein Scribd-Unternehmen logo
1 von 44
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

Weitere ähnliche Inhalte

Was ist angesagt?

Functions in C++
Functions in C++Functions in C++
Functions in C++home
 
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
 
C++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIAC++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIADheeraj Kataria
 
Learning C++ - Functions in C++ 3
Learning C++ - Functions  in C++ 3Learning C++ - Functions  in C++ 3
Learning C++ - Functions in C++ 3Ali Aminian
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT03062679929
 
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
 

Was ist angesagt? (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++
 

Ähnlich wie Chapter 4

Ähnlich wie 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++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.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
 

Mehr von temkin abdlkader

Mehr von 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
 

Kürzlich hochgeladen

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 

Kürzlich hochgeladen (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 

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