SlideShare a Scribd company logo
C++ Functions
Agenda
1. What is a function?
2. Types of C++ functions:
1. Standard functions
2. User-defined functions
3. C++ function structure
1. Function signature
2. Function body
4. Declaring and Implementing C++ functions
5. Sharing data among functions through function
parameters
– Value parameters
– Reference parameters
2
Functions and subprograms
• The Top-down design appeoach is based on dividing the
main problem into smaller tasks which may be divided
into simpler tasks, then implementing each simple task
by a subprogram or a function
• A C++ function or a subprogram is simply a chunk of
C++ code that has
– A descriptive function name, e.g.
• computeTaxes to compute the taxes for an employee
• isPrime to check whether or not a number is a prime number
– A returning value
• The computeTaxes function may return with a double number
representing the amount of taxes
• The isPrime function may return with a Boolean value (true or false)
3
C++ Standard Functions
• C++ language is shipped with a lot of functions
which are known as standard functions
• These standard functions are groups in different
libraries which can be included in the C++
program, e.g.
– Math functions are declared in <math.h> library
– Character-manipulation functions are declared in
<ctype.h> library
– C++ is shipped with more than 100 standard libraries,
some of them are very popular such as <iostream.h>
and <stdlib.h>, others are very specific to certain
hardware platform, e.g. <limits.h> and <largeInt.h>
4
Example of Using
Standard C++ Math Functions
#include <iostream.h>
#include <math.h>
void main()
{
// Getting a double value
double x;
cout << "Please enter a real number: ";
cin >> x;
// Compute the ceiling and the floor of the real number
cout << "The ceil(" << x << ") = " << ceil(x) << endl;
cout << "The floor(" << x << ") = " << floor(x) << endl;
}
5
Example of Using
Standard C++ Character
Functions
#include <iostream.h> // input/output handling
#include <ctype.h> // character type functions
void main()
{
char ch;
cout << "Enter a character: ";
cin >> ch;
cout << "The toupper(" << ch << ") = " << (char) toupper(ch) << endl;
cout << "The tolower(" << ch << ") = " << (char) tolower(ch) << endl;
if (isdigit(ch))
cout << "'" << ch <<"' is a digit!n";
else
cout << "'" << ch <<"' is NOT a digit!n";
}
6
Explicit casting
How to define a C++ Function?
• Generally speaking, we define a C++
function in two steps (preferably but not
mandatory)
– Step #1 – declare the function signature in
either a header file (.h file) or before the main
function of the program
– Step #2 – Implement the function in either an
implementation file (.cpp) or after the main
function
7
8
• Functions
– Modularize a program
– Software reusability
• Call function multiple times
• Local variables
– Known only in the function in which they are
defined
– All variables declared in function definitions
are local variables
• Parameters
– Local variables passed to function when
called
– Provide outside information
What is in a prototype?
A prototype looks like a heading
but must end with a semicolon;
and its parameter list just needs
to contain the type of each
parameter.
int Cube( int ); // prototype
10
Function Definitions
• Function prototype
– Tells compiler argument type and return type of
function
– int square( int );
• Function takes an int and returns an int
– Explained in more detail later
• Calling/invoking a function
– square(x);
– Parentheses an operator used to call function
• Pass argument x
• Function gets its own copy of arguments
– After finished, passes back result
11
Function Definitions
• Format for function definition
return-value-type function-name( parameter-list )
{
declarations and statements
}
– Parameter list
• Comma separated list of arguments
– Data type needed for each argument
• If no arguments, use void or leave blank
– Return-value-type
• Data type of result returned (use void if nothing returned)
A C++ function can return
• in its identifier at most 1 value of the
type which was specified (called the
return type) in its heading and
prototype
• but, a void-function cannot return
any value in its identifier
Classified by Location
Always appear in
a function call
within the calling
block.
Always appear in
the function
heading, or
function
prototype.
Arguments Parameters
Example of User-defined
C++ Function
double computeTax(double income)
{
if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);
return taxes;
}
14
Example of User-defined
C++ Function
double computeTax(double income)
{
if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);
return taxes;
}
15
Function
header
Function
body
Function Signature
• The function signature is actually similar to
the function header except in two aspects:
– The parameters’ names may not be specified
in the function signature
– The function signature must be ended by a
semicolon
• Example
double computeTaxes(double) ;
16
Unnamed
Parameter
Semicolon
;
Example
#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)
{
if (income<5000) return 0.0;
return 0.07*(income-5000.0);
}
double getIncome(string prompt)
{
cout << prompt;
double income;
cin >> income;
return income;
}
void printTaxes(double taxes)
{
cout << "The taxes is $" << taxes << endl;
}
17
Sharing Data Among
User-Defined Functions
• There are two ways to share data
among different functions
–Using global variables (very bad practice!)
–Passing data through function parameters
• Value parameters
• Reference parameters
18
II. Using Parameters
• Function Parameters come in two flavors:
– Value parameters – which copy the values of
the function arguments
– Reference parameters – which refer to the
function arguments by other local names and
have the ability to change the values of the
referenced arguments
19
Example of Defining and Using
Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
20
Local Variables
• Local variables are declared inside the function
body and exist as long as the function is running
and destroyed when the function exit
• You have to initialize the local variable before
using it
• If a function defines a local variable and there
was a global variable with the same name, the
function uses its local variable instead of using
the global variable
21
Example of Defining and Using
Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
22
x 0
Global variables are
automatically initialized to 0
Example of Defining and Using
Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
23
x 0
void main()
{
x = 4;
fun();
cout << x << endl;
}
1
Reference Parameters
• In value parameters any changes in the value
parameters don’t affect the original function
arguments
• Sometimes, we want to change the values of the
original function arguments or return with more
than one value from the function, in this case we
use reference parameters
– A reference parameter is just another name to the
original argument variable
– We define a reference parameter by adding the & in
front of the parameter name, e.g.
double update (double & x);
24
Example of Reference
Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5;
}
void main()
{
int x = 4; // Local variable
fun(x);
cout << x << endl;
}
25
void main()
{
int x = 4;
fun(x);
cout << x << endl;
}
1 x
? x
4

More Related Content

PPT
C++ functions
PPT
C++ functions
PPT
C++ Functions.ppt
PPT
power point presentation on object oriented programming functions concepts
PPT
Functions in c++
PPT
C++ functions presentation by DHEERAJ KATARIA
PPT
C++ functions
PPT
C++ Functions
C++ functions
C++ functions
C++ Functions.ppt
power point presentation on object oriented programming functions concepts
Functions in c++
C++ functions presentation by DHEERAJ KATARIA
C++ functions
C++ Functions

Similar to C++ Functions.ppt (20)

PPTX
Chapter 4
PPTX
Functions in C++
PPTX
Chapter 1 (2) array and structure r.pptx
PDF
PPT
PPT
Chapter Introduction to Modular Programming.ppt
PPT
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
PPTX
Programming Fundamentals lecture-10.pptx
PPTX
Functions in C++
PPT
POLITEKNIK MALAYSIA
PPTX
Fundamental of programming Fundamental of programming
PPT
Lecture 4
PPT
Chapter 1.ppt
PPTX
C++ Functions.pptx
PPTX
FUNCTIONS, CLASSES AND OBJECTS.pptx
PPTX
Intro To C++ - Class #19: Functions
PDF
PPTX
Function C++
PDF
Cpp functions
PPTX
CHAPTER THREE FUNCTION.pptx
Chapter 4
Functions in C++
Chapter 1 (2) array and structure r.pptx
Chapter Introduction to Modular Programming.ppt
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
Programming Fundamentals lecture-10.pptx
Functions in C++
POLITEKNIK MALAYSIA
Fundamental of programming Fundamental of programming
Lecture 4
Chapter 1.ppt
C++ Functions.pptx
FUNCTIONS, CLASSES AND OBJECTS.pptx
Intro To C++ - Class #19: Functions
Function C++
Cpp functions
CHAPTER THREE FUNCTION.pptx
Ad

Recently uploaded (20)

PDF
Clinical guidelines as a resource for EBP(1).pdf
PPTX
climate analysis of Dhaka ,Banglades.pptx
PPTX
Acceptance and paychological effects of mandatory extra coach I classes.pptx
PDF
.pdf is not working space design for the following data for the following dat...
PPTX
modul_python (1).pptx for professional and student
PPTX
Supervised vs unsupervised machine learning algorithms
PDF
Transcultural that can help you someday.
PPTX
oil_refinery_comprehensive_20250804084928 (1).pptx
PPTX
MODULE 8 - DISASTER risk PREPAREDNESS.pptx
PPTX
Data_Analytics_and_PowerBI_Presentation.pptx
PDF
Business Analytics and business intelligence.pdf
PPTX
SAP 2 completion done . PRESENTATION.pptx
PDF
Galatica Smart Energy Infrastructure Startup Pitch Deck
PPTX
Introduction-to-Cloud-ComputingFinal.pptx
PDF
22.Patil - Early prediction of Alzheimer’s disease using convolutional neural...
PPTX
Leprosy and NLEP programme community medicine
PPTX
IBA_Chapter_11_Slides_Final_Accessible.pptx
PPTX
Introduction to Firewall Analytics - Interfirewall and Transfirewall.pptx
PPTX
The THESIS FINAL-DEFENSE-PRESENTATION.pptx
PPTX
IB Computer Science - Internal Assessment.pptx
Clinical guidelines as a resource for EBP(1).pdf
climate analysis of Dhaka ,Banglades.pptx
Acceptance and paychological effects of mandatory extra coach I classes.pptx
.pdf is not working space design for the following data for the following dat...
modul_python (1).pptx for professional and student
Supervised vs unsupervised machine learning algorithms
Transcultural that can help you someday.
oil_refinery_comprehensive_20250804084928 (1).pptx
MODULE 8 - DISASTER risk PREPAREDNESS.pptx
Data_Analytics_and_PowerBI_Presentation.pptx
Business Analytics and business intelligence.pdf
SAP 2 completion done . PRESENTATION.pptx
Galatica Smart Energy Infrastructure Startup Pitch Deck
Introduction-to-Cloud-ComputingFinal.pptx
22.Patil - Early prediction of Alzheimer’s disease using convolutional neural...
Leprosy and NLEP programme community medicine
IBA_Chapter_11_Slides_Final_Accessible.pptx
Introduction to Firewall Analytics - Interfirewall and Transfirewall.pptx
The THESIS FINAL-DEFENSE-PRESENTATION.pptx
IB Computer Science - Internal Assessment.pptx
Ad

C++ Functions.ppt

  • 2. Agenda 1. What is a function? 2. Types of C++ functions: 1. Standard functions 2. User-defined functions 3. C++ function structure 1. Function signature 2. Function body 4. Declaring and Implementing C++ functions 5. Sharing data among functions through function parameters – Value parameters – Reference parameters 2
  • 3. Functions and subprograms • The Top-down design appeoach is based on dividing the main problem into smaller tasks which may be divided into simpler tasks, then implementing each simple task by a subprogram or a function • A C++ function or a subprogram is simply a chunk of C++ code that has – A descriptive function name, e.g. • computeTaxes to compute the taxes for an employee • isPrime to check whether or not a number is a prime number – A returning value • The computeTaxes function may return with a double number representing the amount of taxes • The isPrime function may return with a Boolean value (true or false) 3
  • 4. C++ Standard Functions • C++ language is shipped with a lot of functions which are known as standard functions • These standard functions are groups in different libraries which can be included in the C++ program, e.g. – Math functions are declared in <math.h> library – Character-manipulation functions are declared in <ctype.h> library – C++ is shipped with more than 100 standard libraries, some of them are very popular such as <iostream.h> and <stdlib.h>, others are very specific to certain hardware platform, e.g. <limits.h> and <largeInt.h> 4
  • 5. Example of Using Standard C++ Math Functions #include <iostream.h> #include <math.h> void main() { // Getting a double value double x; cout << "Please enter a real number: "; cin >> x; // Compute the ceiling and the floor of the real number cout << "The ceil(" << x << ") = " << ceil(x) << endl; cout << "The floor(" << x << ") = " << floor(x) << endl; } 5
  • 6. Example of Using Standard C++ Character Functions #include <iostream.h> // input/output handling #include <ctype.h> // character type functions void main() { char ch; cout << "Enter a character: "; cin >> ch; cout << "The toupper(" << ch << ") = " << (char) toupper(ch) << endl; cout << "The tolower(" << ch << ") = " << (char) tolower(ch) << endl; if (isdigit(ch)) cout << "'" << ch <<"' is a digit!n"; else cout << "'" << ch <<"' is NOT a digit!n"; } 6 Explicit casting
  • 7. How to define a C++ Function? • Generally speaking, we define a C++ function in two steps (preferably but not mandatory) – Step #1 – declare the function signature in either a header file (.h file) or before the main function of the program – Step #2 – Implement the function in either an implementation file (.cpp) or after the main function 7
  • 8. 8 • Functions – Modularize a program – Software reusability • Call function multiple times • Local variables – Known only in the function in which they are defined – All variables declared in function definitions are local variables • Parameters – Local variables passed to function when called – Provide outside information
  • 9. What is in a prototype? A prototype looks like a heading but must end with a semicolon; and its parameter list just needs to contain the type of each parameter. int Cube( int ); // prototype
  • 10. 10 Function Definitions • Function prototype – Tells compiler argument type and return type of function – int square( int ); • Function takes an int and returns an int – Explained in more detail later • Calling/invoking a function – square(x); – Parentheses an operator used to call function • Pass argument x • Function gets its own copy of arguments – After finished, passes back result
  • 11. 11 Function Definitions • Format for function definition return-value-type function-name( parameter-list ) { declarations and statements } – Parameter list • Comma separated list of arguments – Data type needed for each argument • If no arguments, use void or leave blank – Return-value-type • Data type of result returned (use void if nothing returned)
  • 12. A C++ function can return • in its identifier at most 1 value of the type which was specified (called the return type) in its heading and prototype • but, a void-function cannot return any value in its identifier
  • 13. Classified by Location Always appear in a function call within the calling block. Always appear in the function heading, or function prototype. Arguments Parameters
  • 14. Example of User-defined C++ Function double computeTax(double income) { if (income < 5000.0) return 0.0; double taxes = 0.07 * (income-5000.0); return taxes; } 14
  • 15. Example of User-defined C++ Function double computeTax(double income) { if (income < 5000.0) return 0.0; double taxes = 0.07 * (income-5000.0); return taxes; } 15 Function header Function body
  • 16. Function Signature • The function signature is actually similar to the function header except in two aspects: – The parameters’ names may not be specified in the function signature – The function signature must be ended by a semicolon • Example double computeTaxes(double) ; 16 Unnamed Parameter Semicolon ;
  • 17. Example #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) { if (income<5000) return 0.0; return 0.07*(income-5000.0); } double getIncome(string prompt) { cout << prompt; double income; cin >> income; return income; } void printTaxes(double taxes) { cout << "The taxes is $" << taxes << endl; } 17
  • 18. Sharing Data Among User-Defined Functions • There are two ways to share data among different functions –Using global variables (very bad practice!) –Passing data through function parameters • Value parameters • Reference parameters 18
  • 19. II. Using Parameters • Function Parameters come in two flavors: – Value parameters – which copy the values of the function arguments – Reference parameters – which refer to the function arguments by other local names and have the ability to change the values of the referenced arguments 19
  • 20. Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } 20
  • 21. Local Variables • Local variables are declared inside the function body and exist as long as the function is running and destroyed when the function exit • You have to initialize the local variable before using it • If a function defines a local variable and there was a global variable with the same name, the function uses its local variable instead of using the global variable 21
  • 22. Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } 22 x 0 Global variables are automatically initialized to 0
  • 23. Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } 23 x 0 void main() { x = 4; fun(); cout << x << endl; } 1
  • 24. Reference Parameters • In value parameters any changes in the value parameters don’t affect the original function arguments • Sometimes, we want to change the values of the original function arguments or return with more than one value from the function, in this case we use reference parameters – A reference parameter is just another name to the original argument variable – We define a reference parameter by adding the & in front of the parameter name, e.g. double update (double & x); 24
  • 25. Example of Reference Parameters #include <iostream.h> void fun(int &y) { cout << y << endl; y=y+5; } void main() { int x = 4; // Local variable fun(x); cout << x << endl; } 25 void main() { int x = 4; fun(x); cout << x << endl; } 1 x ? x 4