Introduction to Functions
NUML
C++ Functions
• A function is a block of code that performs a
specific task.
• Suppose we need to create a calculator program.
– Instead of writing the logic for sum, subtract, multiply
and divide in the main() function, we can create
multiple functions for each logic
• Dividing a complex problem into smaller chunks
makes our program easy to understand and
reusable.
2
Types of Function
There are two types of function:
1. Standard Library Functions: Predefined in C++
2. User-defined Function: Created by users
3
1. User-defined Function
• C++ allows the programmer to define their own
function.
• A user-defined function groups code to perform a
specific task and that group of code is given a name
(identifier).
• When the function is invoked from any part of the
program, it all executes the codes defined in the
body of the function.
Function Declaration
• The syntax to declare a function is:
Calling a Function
• The syntax to declare a function is:
How Function works in C++
• The syntax to declare a function is:
Example 1: Display a Text
Function Parameters
• A function can be declared with parameters (arguments). A
parameter is a value that is passed when declaring a
function.
• For example, let us consider the function below:
Here, the int variable num is the function parameter.
Example 2: Function with Parameters
10
Continue…..
Return Statement
12
Continue…..
13
Example 3: Add Two Numbers
14
Continue…..
15
Function Prototype
16
Continue….
17
Example 4: C++ Function Prototype
18
Benefits of Using User-Defined
Functions
• Functions make the code reusable. We can
declare them once and use them multiple times.
• Functions make the program easier as each small
task is divided into a function.
• Functions increase readability.
19
C++ Library Functions
• Library functions are the built-in functions in C++ programming.
• Programmers can use library functions by invoking the functions
directly; they don't need to write the functions themselves.
• Some common library functions in C++ are sqrt(), isdigit(),
etc.
• In order to use library functions, we usually need to include the
header file in which these library functions are defined.
• For instance, in order to use mathematical functions
such as sqrt(), isdigit()we need to include the header file
cmath.
20
Example 5: Program to Find the
Square Root of a Number
21
Continue…..
22
C++ Pass by Value vs. Pass by Reference
• In above examples, we learned about passing
arguments to a function. This method used is called
passing by value because the actual value is passed.
• However, there is another way of passing arguments
to a function where the actual values of arguments
are not passed. Instead, the reference to values is
passed.
23
C++ Pass by Value vs. Pass by
Reference
24
C++ Pass by Value vs. Pass by Reference
25
Example 6: Passing by reference
26
Continue….
27