SlideShare ist ein Scribd-Unternehmen logo
1 von 21
Page  1
Headline
Placeholder for your own sub headline
C++ Functions
Page  2
AgendaAgenda
• What is a function?What is a function?
• Types of C++ functions:Types of C++ functions:
– Standard functionsStandard functions
• C++ function structureC++ function structure
– Function signatureFunction signature
– Function bodyFunction body
• Declaring andDeclaring and
Implementing C++Implementing C++
functionsfunctions
• Scope of variablesScope of variables
– Local VariablesLocal Variables
– Global variableGlobal variable
• function parametersfunction parameters
– Value parametersValue parameters
– Reference parametersReference parameters
– Const referenceConst reference
parametersparameters
Page  3
What is a function?What is a function?
The Top-down design approach is based on dividing the main problem intoThe Top-down design approach is based on dividing the main problem into
smaller tasks which may be divided into simpler tasks, then implementingsmaller tasks which may be divided into simpler tasks, then implementing
each simple task by a subprogram or a function.each simple task by a subprogram or a function.
In ++ a Function is a group of statements that is given a name and which canIn ++ a Function is a group of statements that is given a name and which can
be called from some point of the program.be called from some point of the program.
•The most common syntax to define a function is :The most common syntax to define a function is :
type name ( parameter1,parameter2,..) { statements }type name ( parameter1,parameter2,..) { statements }
Page  4
C++ Standard FunctionsC++ Standard Functions
• C++ language is shipped with a lot of functionsC++ language is shipped with a lot of functions
which are known as standard functionswhich are known as standard functions
• These standard functions are groups in differentThese standard functions are groups in different
libraries which can be included in the C++libraries which can be included in the C++
program, e.g.program, e.g.
– Math functions are declared in <math.h> libraryMath functions are declared in <math.h> library
– Character-manipulation functions are declared inCharacter-manipulation functions are declared in
<ctype.h> library<ctype.h> library
– C++ is shipped with more than 100 standard libraries,C++ is shipped with more than 100 standard libraries,
some of them are very popular such as <iostream.h>some of them are very popular such as <iostream.h>
and <stdlib.h>, others are very specific to certainand <stdlib.h>, others are very specific to certain
hardware platform, e.g. <limits.h> and <largeInt.h>hardware platform, e.g. <limits.h> and <largeInt.h>
Page  5
Example of UsingExample of Using
Standard C++ Math FunctionsStandard C++ Math Functions
#include <iostream.h>#include <iostream.h>
#include <math.h>#include <math.h>
void main()void main()
{{
// Getting a double value// Getting a double value
double x;double x;
cout << "Please enter a real number: ";cout << "Please enter a real number: ";
cin >> x;cin >> x;
// Compute the ceiling and the floor of the real number// Compute the ceiling and the floor of the real number
cout << "The ceil(" << x << ") = " << ceil(x) << endl;cout << "The ceil(" << x << ") = " << ceil(x) << endl;
cout << "The floor(" << x << ") = " << floor(x) << endl;cout << "The floor(" << x << ") = " << floor(x) << endl;
}}
Page  6
What is The Syntactic Structure ofWhat is The Syntactic Structure of
a C++ Function?a C++ Function?
• A C++ function consists of two partsA C++ function consists of two parts
– The function header, andThe function header, and
– The function bodyThe function body
• The function header has the followingThe function header has the following
syntaxsyntax
<return value> <name> (<parameter list>)<return value> <name> (<parameter list>)
• The function body is simply a C++ codeThe function body is simply a C++ code
enclosed between { }enclosed between { }
Page  7
ExampleExample
{{
if (income < 5000.0) return 0.0;if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);double taxes = 0.07 * (income-5000.0);
return taxes;return taxes;
}}
Function
header
double compute Tax(double income)double compute Tax(double income)double compute Tax(double income)double compute Tax(double income)
Function
body
Function
body
Page  8
Function SignatureFunction Signature
• The function signature is actually similar toThe function signature is actually similar to
the function header except in two aspects:the function header except in two aspects:
– The parametersThe parameters’ names may not be specified’ names may not be specified
in the function signaturein the function signature
– The function signature must be ended by aThe function signature must be ended by a
semicolonsemicolon
• ExampleExample
double computeTaxes(double) ;double computeTaxes(double) ;
Unnamed
Parameter
Semicolon
;
Page  9
Why Do We Need Function Signature?Why Do We Need Function Signature?
For Information Hiding
If you want to create your own library and share it with your
customers without letting them know the implementation
details, you should declare all the function signatures in a
header (.h) file and distribute the binary code of the
implementation file
For Function Abstraction
By only sharing the function signatures, we have the liberty
to change the implementation details from time to time to
Improve function performance
make the customers focus on the purpose of the function, not its
implementation
Page  10
ExampleExample
#include <iostream>
#include <string>
using namespace std;
// Function Signature
double getIncome(string);
double computeTaxes(double);
void printTaxes(double);
void main()
{
// Get the income;
double income = getIncome("Please enter
the employee income: ");
// Compute Taxes
double taxes = computeTaxes(income);
// Print employee taxes
printTaxes(taxes);
}
double computeTaxes(double income)double computeTaxes(double income)
{{
if (income<5000) return 0.0;if (income<5000) return 0.0;
return 0.07*(income-5000.0);return 0.07*(income-5000.0);
}}
double getIncome(string prompt)double getIncome(string prompt)
{{
cout << prompt;cout << prompt;
double income;double income;
cin >> income;cin >> income;
return income;return income;
}}
void printTaxes(double taxes)void printTaxes(double taxes)
{{
cout << "The taxes is $" << taxes <<cout << "The taxes is $" << taxes <<
endl;endl;
}}
Page  11
C++ VariablesC++ Variables
• A variable is a place in memory that has :A variable is a place in memory that has :
– A name or identifier (e.g. income, taxes, etc.)A name or identifier (e.g. income, taxes, etc.)
– A data type (e.g. int, double, char, etc.)A data type (e.g. int, double, char, etc.)
– A size (number of bytes)A size (number of bytes)
– A scope (the part of the program code that can use it)A scope (the part of the program code that can use it)
• Global variables – all functions can see it and using itGlobal variables – all functions can see it and using it
• Local variables – only the function that declare localLocal variables – only the function that declare local
variables see and use these variablesvariables see and use these variables
– A life time (the duration of its existence)A life time (the duration of its existence)
• Global variables can live as long as the program is executedGlobal variables can live as long as the program is executed
• Local variables are lived only when the functions that defineLocal variables are lived only when the functions that define
these variables are executedthese variables are executed
Page  12
I. Using Global VariablesI. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}
Page  13
Local VariablesLocal Variables
• Local variables are declared inside the functionLocal variables are declared inside the function
body and exist as long as the function is runningbody and exist as long as the function is running
and destroyed when the function exitand destroyed when the function exit
• You have to initialize the local variable beforeYou have to initialize the local variable before
using itusing it
• If a function defines a local variable and thereIf a function defines a local variable and there
was a global variable with the same name, thewas a global variable with the same name, the
function uses its local variable instead of usingfunction uses its local variable instead of using
the global variablethe global variable
Page  14
Example of Using Global and LocalExample of Using Global and Local
VariablesVariables#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
Void fun();Void fun(); // function signature// function signature
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
void fun()void fun()
{{
int x = 10;int x = 10; // Local variable// Local variable
cout << x << endl;cout << x << endl;
}}
Page  15
Using ParametersUsing Parameters
• Function Parameters come in threeFunction Parameters come in three
flavors:flavors:
– Value parametersValue parameters – which copy the values of– which copy the values of
the function argumentsthe function arguments
– Reference parametersReference parameters – which refer to the– which refer to the
function arguments by other local names andfunction arguments by other local names and
have the ability to change the values of thehave the ability to change the values of the
referenced argumentsreferenced arguments
– Constant reference parametersConstant reference parameters – similar to– similar to
the reference parameters but cannot changethe reference parameters but cannot change
the values of the referenced argumentsthe values of the referenced arguments
Page  16
Value ParametersValue Parameters
• This is what we use to declare in the function signature orThis is what we use to declare in the function signature or
function header, e.g.function header, e.g.
int max (int x, int y);int max (int x, int y);
– Here, parameters x and y are value parametersHere, parameters x and y are value parameters
– When you call the max function asWhen you call the max function as max(4, 7)max(4, 7), the values 4 and 7, the values 4 and 7
are copied to x and y respectivelyare copied to x and y respectively
– When you call the max function asWhen you call the max function as max (a, b),max (a, b), where a=40 andwhere a=40 and
b=10, the values 40 and 10 are copied to x and y respectivelyb=10, the values 40 and 10 are copied to x and y respectively
– When you call the max function asWhen you call the max function as max( a+b, b/2),max( a+b, b/2), the values 50the values 50
and 5 are copies to x and y respectivelyand 5 are copies to x and y respectively
• Once the value parameters accepted copies of theOnce the value parameters accepted copies of the
corresponding arguments data, they act as localcorresponding arguments data, they act as local
variables!variables!
Page  17
Example of Using ValueExample of Using Value
Parameters and Global VariablesParameters and Global Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
void fun(int x)void fun(int x)
{{
cout << x << endl;cout << x << endl;
x=x+5;x=x+5;
}}
void main()void main()
{{
x = 4;x = 4;
fun(x/2+1);fun(x/2+1);
cout << x << endl;cout << x << endl;
}}
Page  18
Reference ParametersReference Parameters
• As we saw in the last example, any changes inAs we saw in the last example, any changes in
the value parameters donthe value parameters don’t affect the original’t affect the original
function argumentsfunction arguments
• Sometimes, we want to change the values of theSometimes, we want to change the values of the
original function arguments or return with moreoriginal function arguments or return with more
than one value from the function, in this case wethan one value from the function, in this case we
use reference parametersuse reference parameters
– A reference parameter is just another name to theA reference parameter is just another name to the
original argument variableoriginal argument variable
– We define a reference parameter by adding the & inWe define a reference parameter by adding the & in
front of the parameter name, e.g.front of the parameter name, e.g.
double update (double & x);double update (double & x);
Page  19
Example of Reference ParametersExample of Reference Parameters
#include <iostream.h>#include <iostream.h>
void fun(int &y)void fun(int &y)
{{
cout << y << endl;cout << y << endl;
y=y+5;y=y+5;
}}
void main()void main()
{{
int x = 4; // Local variableint x = 4; // Local variable
fun(x);fun(x);
cout << x << endl;cout << x << endl;
}}
Page  20
Constant Reference ParametersConstant Reference Parameters
• Constant reference parameters are used underConstant reference parameters are used under
the following two conditions:the following two conditions:
– The passed data are so big and you want to saveThe passed data are so big and you want to save
time and computer memorytime and computer memory
– The passed data will not be changed or updated inThe passed data will not be changed or updated in
the function bodythe function body
• For exampleFor example
void report (const string & prompt);void report (const string & prompt);
• The only valid arguments accepted by referenceThe only valid arguments accepted by reference
parameters and constant reference parametersparameters and constant reference parameters
are variable namesare variable names
– It is a syntax error to pass constant values orIt is a syntax error to pass constant values or
expressions to the (const) reference parametersexpressions to the (const) reference parameters
Page  21
www.cplusplus.com
www.wikipedia.org
www.cplusplus.com
www.wikipedia.org Student Name : Abdullah Mohammed
Turkistani
Student No :214371603
Instructor :Mr.Ibrahim Al-Odaini
Sources :

Weitere ähnliche Inhalte

Was ist angesagt?

Unit 5. Control Statement
Unit 5. Control StatementUnit 5. Control Statement
Unit 5. Control StatementAshim Lamichhane
 
Tokens expressionsin C++
Tokens expressionsin C++Tokens expressionsin C++
Tokens expressionsin C++HalaiHansaika
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C v_jk
 
Programming in C Presentation upto FILE
Programming in C Presentation upto FILEProgramming in C Presentation upto FILE
Programming in C Presentation upto FILEDipta Saha
 
user defined function
user defined functionuser defined function
user defined functionKing Kavin Patel
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
Function in c
Function in cFunction in c
Function in csavitamhaske
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptAmanuelZewdie4
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default argumentsNikhil Pandit
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++HalaiHansaika
 
What are variables and keywords in c++
What are variables and keywords in c++What are variables and keywords in c++
What are variables and keywords in c++Abdul Hafeez
 
Scope rules : local and global variables
Scope rules : local and global variablesScope rules : local and global variables
Scope rules : local and global variablessangrampatil81
 
Functions in c language
Functions in c language Functions in c language
Functions in c language tanmaymodi4
 

Was ist angesagt? (20)

Python Modules
Python ModulesPython Modules
Python Modules
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
 
Unit 5. Control Statement
Unit 5. Control StatementUnit 5. Control Statement
Unit 5. Control Statement
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Tokens expressionsin C++
Tokens expressionsin C++Tokens expressionsin C++
Tokens expressionsin C++
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
Programming in C Presentation upto FILE
Programming in C Presentation upto FILEProgramming in C Presentation upto FILE
Programming in C Presentation upto FILE
 
user defined function
user defined functionuser defined function
user defined function
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Function in c
Function in cFunction in c
Function in c
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.ppt
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
What are variables and keywords in c++
What are variables and keywords in c++What are variables and keywords in c++
What are variables and keywords in c++
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
Scope rules : local and global variables
Scope rules : local and global variablesScope rules : local and global variables
Scope rules : local and global variables
 
Templates
TemplatesTemplates
Templates
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 

Andere mochten auch

Functions in C++
Functions in C++Functions in C++
Functions in C++home
 
functions of C++
functions of C++functions of C++
functions of C++tarandeep_kaur
 
Intro. to prog. c++
Intro. to prog. c++Intro. to prog. c++
Intro. to prog. c++KurdGul
 
Part 3-functions
Part 3-functionsPart 3-functions
Part 3-functionsankita44
 
Csc1100 lecture06 ch06_pt2
Csc1100 lecture06 ch06_pt2Csc1100 lecture06 ch06_pt2
Csc1100 lecture06 ch06_pt2IIUM
 
Object Oriented Program
Object Oriented ProgramObject Oriented Program
Object Oriented ProgramAlisha Jain
 
C++ arrays part2
C++ arrays part2C++ arrays part2
C++ arrays part2Subhasis Nayak
 
Random number generation (in C++) – past, present and potential future
Random number generation (in C++) – past, present and potential future Random number generation (in C++) – past, present and potential future
Random number generation (in C++) – past, present and potential future Pattabi Raman
 
Netw450 advanced network security with lab entire class
Netw450 advanced network security with lab entire classNetw450 advanced network security with lab entire class
Netw450 advanced network security with lab entire classEugenioBrown1
 
C++
C++C++
C++dean129
 
Flow control in c++
Flow control in c++Flow control in c++
Flow control in c++Subhasis Nayak
 
Functions c++ مشروع
Functions c++ مشروعFunctions c++ مشروع
Functions c++ مشروعziadalmulla
 
Network-security muhibullah aman-first edition-in Persian
Network-security muhibullah aman-first edition-in PersianNetwork-security muhibullah aman-first edition-in Persian
Network-security muhibullah aman-first edition-in PersianMuhibullah Aman
 
Network Security in 2016
Network Security in 2016Network Security in 2016
Network Security in 2016Qrator Labs
 
Learning C++ - Functions in C++ 3
Learning C++ - Functions  in C++ 3Learning C++ - Functions  in C++ 3
Learning C++ - Functions in C++ 3Ali Aminian
 

Andere mochten auch (20)

Functions in C++
Functions in C++Functions in C++
Functions in C++
 
functions of C++
functions of C++functions of C++
functions of C++
 
Intro. to prog. c++
Intro. to prog. c++Intro. to prog. c++
Intro. to prog. c++
 
Part 3-functions
Part 3-functionsPart 3-functions
Part 3-functions
 
Csc1100 lecture06 ch06_pt2
Csc1100 lecture06 ch06_pt2Csc1100 lecture06 ch06_pt2
Csc1100 lecture06 ch06_pt2
 
C++ programming
C++ programmingC++ programming
C++ programming
 
Object Oriented Program
Object Oriented ProgramObject Oriented Program
Object Oriented Program
 
C++ arrays part2
C++ arrays part2C++ arrays part2
C++ arrays part2
 
Random number generation (in C++) – past, present and potential future
Random number generation (in C++) – past, present and potential future Random number generation (in C++) – past, present and potential future
Random number generation (in C++) – past, present and potential future
 
C++11
C++11C++11
C++11
 
C++ L05-Functions
C++ L05-FunctionsC++ L05-Functions
C++ L05-Functions
 
Netw450 advanced network security with lab entire class
Netw450 advanced network security with lab entire classNetw450 advanced network security with lab entire class
Netw450 advanced network security with lab entire class
 
C++
C++C++
C++
 
Flow control in c++
Flow control in c++Flow control in c++
Flow control in c++
 
Functions c++ مشروع
Functions c++ مشروعFunctions c++ مشروع
Functions c++ مشروع
 
C++ revision tour
C++ revision tourC++ revision tour
C++ revision tour
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Network-security muhibullah aman-first edition-in Persian
Network-security muhibullah aman-first edition-in PersianNetwork-security muhibullah aman-first edition-in Persian
Network-security muhibullah aman-first edition-in Persian
 
Network Security in 2016
Network Security in 2016Network Security in 2016
Network Security in 2016
 
Learning C++ - Functions in C++ 3
Learning C++ - Functions  in C++ 3Learning C++ - Functions  in C++ 3
Learning C++ - Functions in C++ 3
 

Ähnlich wie Functions in c++

C++ Functions
C++ FunctionsC++ Functions
C++ Functionssathish sak
 
C++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIAC++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIADheeraj Kataria
 
C++ functions
C++ functionsC++ functions
C++ functionsMayank Jain
 
C++ functions
C++ functionsC++ functions
C++ functionsDawood Jutt
 
C++ functions
C++ functionsC++ functions
C++ functionsDawood Jutt
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++LPU
 
power point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions conceptspower point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions conceptsbhargavi804095
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 FunctionDeepak Singh
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.pptWaheedAnwar20
 
C structure
C structureC structure
C structureankush9927
 
Presentation c++
Presentation c++Presentation c++
Presentation c++JosephAlex21
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAAiman Hud
 

Ähnlich wie Functions in c++ (20)

C++ Functions
C++ FunctionsC++ Functions
C++ Functions
 
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
 
C++ functions
C++ functionsC++ functions
C++ functions
 
C++ functions
C++ functionsC++ functions
C++ functions
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
power point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions conceptspower point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions concepts
 
Function
FunctionFunction
Function
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 Function
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
4th unit full
4th unit full4th unit full
4th unit full
 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
 
C structure
C structureC structure
C structure
 
Basics of cpp
Basics of cppBasics of cpp
Basics of cpp
 
Presentation c++
Presentation c++Presentation c++
Presentation c++
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Function
Function Function
Function
 

KĂźrzlich hochgeladen

Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
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
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
🐬 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
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
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
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

KĂźrzlich hochgeladen (20)

Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
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
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

Functions in c++

  • 1. Page  1 Headline Placeholder for your own sub headline C++ Functions
  • 2. Page  2 AgendaAgenda • What is a function?What is a function? • Types of C++ functions:Types of C++ functions: – Standard functionsStandard functions • C++ function structureC++ function structure – Function signatureFunction signature – Function bodyFunction body • Declaring andDeclaring and Implementing C++Implementing C++ functionsfunctions • Scope of variablesScope of variables – Local VariablesLocal Variables – Global variableGlobal variable • function parametersfunction parameters – Value parametersValue parameters – Reference parametersReference parameters – Const referenceConst reference parametersparameters
  • 3. Page  3 What is a function?What is a function? The Top-down design approach is based on dividing the main problem intoThe Top-down design approach is based on dividing the main problem into smaller tasks which may be divided into simpler tasks, then implementingsmaller tasks which may be divided into simpler tasks, then implementing each simple task by a subprogram or a function.each simple task by a subprogram or a function. In ++ a Function is a group of statements that is given a name and which canIn ++ a Function is a group of statements that is given a name and which can be called from some point of the program.be called from some point of the program. •The most common syntax to define a function is :The most common syntax to define a function is : type name ( parameter1,parameter2,..) { statements }type name ( parameter1,parameter2,..) { statements }
  • 4. Page  4 C++ Standard FunctionsC++ Standard Functions • C++ language is shipped with a lot of functionsC++ language is shipped with a lot of functions which are known as standard functionswhich are known as standard functions • These standard functions are groups in differentThese standard functions are groups in different libraries which can be included in the C++libraries which can be included in the C++ program, e.g.program, e.g. – Math functions are declared in <math.h> libraryMath functions are declared in <math.h> library – Character-manipulation functions are declared inCharacter-manipulation functions are declared in <ctype.h> library<ctype.h> library – C++ is shipped with more than 100 standard libraries,C++ is shipped with more than 100 standard libraries, some of them are very popular such as <iostream.h>some of them are very popular such as <iostream.h> and <stdlib.h>, others are very specific to certainand <stdlib.h>, others are very specific to certain hardware platform, e.g. <limits.h> and <largeInt.h>hardware platform, e.g. <limits.h> and <largeInt.h>
  • 5. Page  5 Example of UsingExample of Using Standard C++ Math FunctionsStandard C++ Math Functions #include <iostream.h>#include <iostream.h> #include <math.h>#include <math.h> void main()void main() {{ // Getting a double value// Getting a double value double x;double x; cout << "Please enter a real number: ";cout << "Please enter a real number: "; cin >> x;cin >> x; // Compute the ceiling and the floor of the real number// Compute the ceiling and the floor of the real number cout << "The ceil(" << x << ") = " << ceil(x) << endl;cout << "The ceil(" << x << ") = " << ceil(x) << endl; cout << "The floor(" << x << ") = " << floor(x) << endl;cout << "The floor(" << x << ") = " << floor(x) << endl; }}
  • 6. Page  6 What is The Syntactic Structure ofWhat is The Syntactic Structure of a C++ Function?a C++ Function? • A C++ function consists of two partsA C++ function consists of two parts – The function header, andThe function header, and – The function bodyThe function body • The function header has the followingThe function header has the following syntaxsyntax <return value> <name> (<parameter list>)<return value> <name> (<parameter list>) • The function body is simply a C++ codeThe function body is simply a C++ code enclosed between { }enclosed between { }
  • 7. Page  7 ExampleExample {{ if (income < 5000.0) return 0.0;if (income < 5000.0) return 0.0; double taxes = 0.07 * (income-5000.0);double taxes = 0.07 * (income-5000.0); return taxes;return taxes; }} Function header double compute Tax(double income)double compute Tax(double income)double compute Tax(double income)double compute Tax(double income) Function body Function body
  • 8. Page  8 Function SignatureFunction Signature • The function signature is actually similar toThe function signature is actually similar to the function header except in two aspects:the function header except in two aspects: – The parametersThe parameters’ names may not be specified’ names may not be specified in the function signaturein the function signature – The function signature must be ended by aThe function signature must be ended by a semicolonsemicolon • ExampleExample double computeTaxes(double) ;double computeTaxes(double) ; Unnamed Parameter Semicolon ;
  • 9. Page  9 Why Do We Need Function Signature?Why Do We Need Function Signature? For Information Hiding If you want to create your own library and share it with your customers without letting them know the implementation details, you should declare all the function signatures in a header (.h) file and distribute the binary code of the implementation file For Function Abstraction By only sharing the function signatures, we have the liberty to change the implementation details from time to time to Improve function performance make the customers focus on the purpose of the function, not its implementation
  • 10. Page  10 ExampleExample #include <iostream> #include <string> using namespace std; // Function Signature double getIncome(string); double computeTaxes(double); void printTaxes(double); void main() { // Get the income; double income = getIncome("Please enter the employee income: "); // Compute Taxes double taxes = computeTaxes(income); // Print employee taxes printTaxes(taxes); } double computeTaxes(double income)double computeTaxes(double income) {{ if (income<5000) return 0.0;if (income<5000) return 0.0; return 0.07*(income-5000.0);return 0.07*(income-5000.0); }} double getIncome(string prompt)double getIncome(string prompt) {{ cout << prompt;cout << prompt; double income;double income; cin >> income;cin >> income; return income;return income; }} void printTaxes(double taxes)void printTaxes(double taxes) {{ cout << "The taxes is $" << taxes <<cout << "The taxes is $" << taxes << endl;endl; }}
  • 11. Page  11 C++ VariablesC++ Variables • A variable is a place in memory that has :A variable is a place in memory that has : – A name or identifier (e.g. income, taxes, etc.)A name or identifier (e.g. income, taxes, etc.) – A data type (e.g. int, double, char, etc.)A data type (e.g. int, double, char, etc.) – A size (number of bytes)A size (number of bytes) – A scope (the part of the program code that can use it)A scope (the part of the program code that can use it) • Global variables – all functions can see it and using itGlobal variables – all functions can see it and using it • Local variables – only the function that declare localLocal variables – only the function that declare local variables see and use these variablesvariables see and use these variables – A life time (the duration of its existence)A life time (the duration of its existence) • Global variables can live as long as the program is executedGlobal variables can live as long as the program is executed • Local variables are lived only when the functions that defineLocal variables are lived only when the functions that define these variables are executedthese variables are executed
  • 12. Page  12 I. Using Global VariablesI. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; }
  • 13. Page  13 Local VariablesLocal Variables • Local variables are declared inside the functionLocal variables are declared inside the function body and exist as long as the function is runningbody and exist as long as the function is running and destroyed when the function exitand destroyed when the function exit • You have to initialize the local variable beforeYou have to initialize the local variable before using itusing it • If a function defines a local variable and thereIf a function defines a local variable and there was a global variable with the same name, thewas a global variable with the same name, the function uses its local variable instead of usingfunction uses its local variable instead of using the global variablethe global variable
  • 14. Page  14 Example of Using Global and LocalExample of Using Global and Local VariablesVariables#include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable Void fun();Void fun(); // function signature// function signature void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} void fun()void fun() {{ int x = 10;int x = 10; // Local variable// Local variable cout << x << endl;cout << x << endl; }}
  • 15. Page  15 Using ParametersUsing Parameters • Function Parameters come in threeFunction Parameters come in three flavors:flavors: – Value parametersValue parameters – which copy the values of– which copy the values of the function argumentsthe function arguments – Reference parametersReference parameters – which refer to the– which refer to the function arguments by other local names andfunction arguments by other local names and have the ability to change the values of thehave the ability to change the values of the referenced argumentsreferenced arguments – Constant reference parametersConstant reference parameters – similar to– similar to the reference parameters but cannot changethe reference parameters but cannot change the values of the referenced argumentsthe values of the referenced arguments
  • 16. Page  16 Value ParametersValue Parameters • This is what we use to declare in the function signature orThis is what we use to declare in the function signature or function header, e.g.function header, e.g. int max (int x, int y);int max (int x, int y); – Here, parameters x and y are value parametersHere, parameters x and y are value parameters – When you call the max function asWhen you call the max function as max(4, 7)max(4, 7), the values 4 and 7, the values 4 and 7 are copied to x and y respectivelyare copied to x and y respectively – When you call the max function asWhen you call the max function as max (a, b),max (a, b), where a=40 andwhere a=40 and b=10, the values 40 and 10 are copied to x and y respectivelyb=10, the values 40 and 10 are copied to x and y respectively – When you call the max function asWhen you call the max function as max( a+b, b/2),max( a+b, b/2), the values 50the values 50 and 5 are copies to x and y respectivelyand 5 are copies to x and y respectively • Once the value parameters accepted copies of theOnce the value parameters accepted copies of the corresponding arguments data, they act as localcorresponding arguments data, they act as local variables!variables!
  • 17. Page  17 Example of Using ValueExample of Using Value Parameters and Global VariablesParameters and Global Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable void fun(int x)void fun(int x) {{ cout << x << endl;cout << x << endl; x=x+5;x=x+5; }} void main()void main() {{ x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl; }}
  • 18. Page  18 Reference ParametersReference Parameters • As we saw in the last example, any changes inAs we saw in the last example, any changes in the value parameters donthe value parameters don’t affect the original’t affect the original function argumentsfunction arguments • Sometimes, we want to change the values of theSometimes, we want to change the values of the original function arguments or return with moreoriginal function arguments or return with more than one value from the function, in this case wethan one value from the function, in this case we use reference parametersuse reference parameters – A reference parameter is just another name to theA reference parameter is just another name to the original argument variableoriginal argument variable – We define a reference parameter by adding the & inWe define a reference parameter by adding the & in front of the parameter name, e.g.front of the parameter name, e.g. double update (double & x);double update (double & x);
  • 19. Page  19 Example of Reference ParametersExample of Reference Parameters #include <iostream.h>#include <iostream.h> void fun(int &y)void fun(int &y) {{ cout << y << endl;cout << y << endl; y=y+5;y=y+5; }} void main()void main() {{ int x = 4; // Local variableint x = 4; // Local variable fun(x);fun(x); cout << x << endl;cout << x << endl; }}
  • 20. Page  20 Constant Reference ParametersConstant Reference Parameters • Constant reference parameters are used underConstant reference parameters are used under the following two conditions:the following two conditions: – The passed data are so big and you want to saveThe passed data are so big and you want to save time and computer memorytime and computer memory – The passed data will not be changed or updated inThe passed data will not be changed or updated in the function bodythe function body • For exampleFor example void report (const string & prompt);void report (const string & prompt); • The only valid arguments accepted by referenceThe only valid arguments accepted by reference parameters and constant reference parametersparameters and constant reference parameters are variable namesare variable names – It is a syntax error to pass constant values orIt is a syntax error to pass constant values or expressions to the (const) reference parametersexpressions to the (const) reference parameters
  • 21. Page  21 www.cplusplus.com www.wikipedia.org www.cplusplus.com www.wikipedia.org Student Name : Abdullah Mohammed Turkistani Student No :214371603 Instructor :Mr.Ibrahim Al-Odaini Sources :