Chapter 1 - Functions
Chapter 1 - Functions
(SEng2021)
Chapter-One
Functions in C++
1
Contents
Basic concept and need of function
Declaring and defining a function
Function components (parameters and arguments)
Calling /invoking function by value and reference
parameters
Functions Recursion
2
Introduction
Let us imagine an automobile factory. When an automobile is
manufactured, it is not made from basic raw materials; it is put
together from previously manufactured parts. Some parts are
made by the company itself; others, by different companies.
Functions are like building blocks. They let you divide
complicated programs into manageable pieces. They have
other advantages, too:
While working on one function, you can focus on just that part of the
program and construct it, debug it, and perfect it.
Different people can work on different functions simultaneously.
If a function is needed in more than one place in a program or in
different programs, you can write it once and use it many times.
Using functions greatly enhances the program’s readability because
it reduces the complexity of the function main.
Functions are often called modules. They are like miniature
programs; you can put them together to form a larger program.
3
Cont…
A function is a group of statements that together perform a task.
Every C++ program has at least one function, which is main(),
and all the most trivial programs can define additional functions.
A function is a subprogram that acts on data and often returns a
value. A program written with numerous functions is easier to
maintain, update and debug than one very long program.
By programming in a modular (functional) fashion, several
programmers can work independently on separate functions
which can be assembled at a later date to create the entire
project. Each function has its own name. When that name is
encountered in a program, the execution of the program
branches to the body of that function. When the function is
finished, execution returns to the area of the program code from
which it was called, and the program continues on to the next
line of code.
4
Cont…
There are many advantages of functions.
Code Reusability
By creating functions in C++, you can call it many times. So
we don't need to write the same code again and again.
Code optimization
It makes the code optimized, we don't need to write much
code.
Suppose, you have to check 3 numbers (531, 883 and 781)
whether it is prime number or not. Without using function,
you need to write the prime number logic 3 times. So, there
is repetition of code.
6
Cont…
#include
<iostream>
Functions
#include <cmath> From <cmath> Library
using namespace
std;
int main() {
double s = Outpu
sqrt(25.0); t
cout << s << endl; 5
double p = pow(2.0, 8
3.0); 3
cout << p << endl; 4
int a = abs(-10); 3
cout << a << endl;
double f =
floor(3.8);
cout<< f << endl;
double c =
ceil(3.2);
cout << c <<
7 endl; }
Cont…
Functions From <iomanip> Library
Used for output formatting
Nam
Age City
#include <iostream> e
#include <iomanip> New York
using namespace std; John 25
int main() {
Emil << setw(10) << "Age" << setw(10)
cout << setw(10) << "Name" 30 London
y
<< "City" << endl; cout << setw(10) << "John" << setw(10) << 25
<< setw(10) << "New York" << endl;
cout << setw(10) << "Emily" << setw(10) << 30 << setw(10) <<
"London" << endl;
return 0;
8
Cont…
Functions From <iomanip> Library
Used for output formatting
int main() {
cout << left << setw(10) << "Name"; Name Age City
cout << left << setw(10) << "Age";
cout << left << setw(10) << "City" << New York
endl; John 25
cout << left << setw(10) << "John";
cout << left << setw(10) << 25;
cout << left << setw(10) << "New Emily 30 London
York" << endl;
cout << left << setw(10) << "Emily";
cout << left << setw(10) << 30;
cout << left << setw(10) << "London"
<< endl;
9
Cont…
Functions From <iomanip> Library
Used for output formatting
int main() {
double number = 1234.56789;
cout << setprecision(2) << number << endl;
cout << fixed << setprecision(3) << number 1.2e+03
<< endl; 1234.568
cout << setprecision(2) << number << endl; 1234.57
cout<<setiosflags(ios::scientific)<<number< 1.234568e
<endl; +03
return 0;
}
10
Cont…
2. User Defined Function
How functions are defined, used, and organized?
Declaration
Definition
invoking/calling
11
Cont…
By it's definition, a function is a group of code that is
accessed at some point in the execution of a program
which carries out some specific task(s). They are
accessed when they are called.
A function declaration tells the compiler about a
function's name, return type, and parameters. A function
definition provides the actual body of the function.
The C++ standard library provides numerous built-in
functions that your program can call. For example,
function strcat() to concatenate two strings, function
memcpy() to copy one memory location to another
location and many more functions.
A function is knows as with various names like a method
or a sub-routine or a procedure etc.
12
Defining a Function
The general form of a C++ function definition is as follows:
return_type function_name( parameter list )
{
body of the function
}
A C++ function definition consists of a function header and a function body. Here
are all the parts of a function:
Return Type: A function may return a value. The return_type is the data type
of the value the function returns. Some functions perform the desired operations
without returning a value. In this case, the return_type is the keyword void.
Function Name: This is the actual name of the function. The function name and
the parameter list together constitute the function signature.
Parameters: A parameter is like a placeholder. When a function is invoked, you
pass a value to the parameter. This value is referred to as actual parameter or
argument. The parameter list refers to the type, order, and number of the
parameters of a function. Parameters are optional; that is, a function may
contain no parameters.
Function Body: The function body contains a collection of statements that
define what the function does.
13
Function Declarations
A function declaration tells the compiler about a
function name and how to call the function. The actual
body of the function can be defined separately.
A function declaration has the following parts:
return_type function_name( parameter list );
For the above defined function max(), following is the
function declaration:
int max(int num1, int num2);
Parameter names are not important in function
declaration only their type is required, so following is
also valid declaration:
int max(int, int);
14
Cont…
Function declaration is required when you define
a function in one source file and you call that
function in another file. In such case, you should
declare the function at the top of the file calling
#include<iostream.h>
15 << z;
}
Cont…
This program is divided in two functions: addition and
main. Remember that no matter the order in which
they are defined, a C++ program always starts by
calling main. In fact, main is the only function called
automatically, and the code in any other function is
only executed if its function is called from main .
In the example above, main begins by declaring the
variable z of type int, and right after that, it performs
the first function call: it calls addition. The call to a
function follows a structure very similar to its
declaration. In the example above, the call to addition
can be compared to its definition just a few lines
earlier:
16
Cont…
20
Cont…
Similar to the addition function in the previous example, this
example defines a subtract function, that simply returns the
difference between its two parameters. This time, main calls
this function several times, demonstrating more possible
ways in which a function can be called.
Let's examine each of these calls, bearing in mind that each
function call is itself an expression that is evaluated as the
value it returns. Again, you can think of it as if the function
call was itself replaced by the returned value:
1.z = subtraction (7,2);
2.cout << "The first result is " << z;
If we replace the function call by the value it returns (i.e., 5),
we would have:
1.z = 5;
2.cout << "The first result is " << z;
21
Cont…
With the same procedure, we could interpret:
cout << "The second result is " << subtraction (7,2);
As:
cout << "The second result is " << 5;
Since 5 is the value returned by subtraction (7,2).
In the case of:
cout << "The third result is " << subtraction (x,y);
The arguments passed to subtraction are variables instead
of literals. That is also valid, and works fine. The function
is called with the values x and y have at the moment of
the call: 5 and 3 respectively, returning 2 as result.
The fourth call is again similar:
z = 4 + subtraction(x,y);
22
Cont…
The only addition being that now the function call is
also an operand of an addition operation. Again, the
result is the same as if the function call was replaced
by its result: 6. Note, that thanks to the commutative
property of additions, the above can also be written as:
z = subtraction (x,y) + 4;
With exactly the same result. Note also that the
semicolon does not necessarily go after the function
call, but, as always, at the end of the whole statement.
Again, the logic behind may be easily seen again by
replacing the function calls by their returned value:
1. z = 4 + 2; // same as z = 4 + substraction (x,y);
2. z = 2 + 4; // same as z = substraction (x,y) + 4;
23
Functions with no type. The use of
void
The syntax shown above for functions:
type name ( argument1, argument2 ...)
{ statements }
Requires the declaration to begin with a type.
This is the type of the value returned by the
function. But what if the function does not need
to return a value? In this case, the type to be
used is void, which is a special type to represent
the absence of value. For example, a function
that simply prints a message may not need to
return any value:
24
Cont…
// void function example
#include <iostream>
#include<conio.h>
using namespace std;
void printmessage ()
{
cout << "I'm a function!"; I'm a function!
}
int main ()
{
printmessage ();
getch();
}
25
Cont…
void can also be used in the function's
parameter list to explicitly specify that the
function takes no actual parameters when
called. For example, printmessage could have
been declared as:
void printmessage (void)
{
cout << "I'm a function!";
}
26
Cont…
In C++, an empty parameter list can be used instead of void
with same meaning, but the use of void in the argument list
was popularized by the C language, where this is a
requirement.
Something that in no case is optional are the parentheses
that follow the function name, neither in its declaration nor
when calling it. And even when the function takes no
parameters, at least an empty pair of parentheses shall
always be appended to the function name. See how
printmessage was called in an earlier example:
printmessage ();
The parentheses are what differentiate functions from other
kinds of declarations or statements. The following would not
call the function:
Printmessage;
27
Function Prototypes
The function heading without the body of the function.
In C++, the code of function declaration should be before the
function call. However, if we want to define a function after the
function call, we need to use the function prototype. For example,
Function prototype contains
Function name
Parameters (number and data type)
Return type (void if returns nothing)
Only needed if function definition after function call
Prototype must match function definition
Function prototype
double maximum( double, double, double );
Definition
double maximum( double x, double y, double z )
{
…
}
28
Cont…
Function signature
Part of prototype with name and parameters
double maximum( double, double, double );
Function signature
Argument Coercion
Force arguments to be of proper type
Converting int (4) to double (4.0)
cout << sqrt(4)
Conversion rules
Arguments usually converted automatically
Changing from double to int can truncate data
3.4 to 3
Mixed type goes to highest type (promotion)
Int * double
29
Cont…
// function prototype
void add(int, int);
int main()
{ // calling the function before declaration.
add(5, 3);
return 0;
} // function definition
void add(int a, int b)
{
cout << (a + b);
}
30
Calling functions
In order for a function to be used in a program, it must be called. To do this,
the name of the function and any parameters you are passing to it must be
typed out EXACTLY as how you declared it. The below example shows how
to call as well as declare a function:
Below is a program that will show an example of a void function and how it
is called.
// for loop to print out index
#include <iostream>
#include <conio.h>
Using namespace std;
void printMessage(){
cout << "Hello and welcome!" << endl;}
int main(){
printMessage();
return 0;}
As you will observe, when the main function is run, the printMessage()
function is called and prints out the message. Remember the rule of void
functions: they do not return a value.
31
Cont…
Passing by value
When dealing with function parameters, there are two ways of
passing variables or other values. One ways, and the most
common, is called passing by value. This will give a COPY of
the value to the function and the ORIGINAL value WILL NOT
CHANGE IN THE PROGRAM. The below example shows a simple
adding function that tries to change a value but does not.
Below is a program that will show an example of a pass by
value call to a simple adding function.
32
Cont…
// for loop to print out index
#include <iostream>
#include <conio.h>
Using namespace std;
int add( int a, int b ){
int sum = a+b;
a = 7;
return sum;}
int main(){
int n1 = 5, n2 = 6;
cout << add(n1,n2) << endl;
cout << n1 << endl;
return 0;}
This program will pass the variables n1 and n2 to the function add(...) and return
the sum of those two numbers.
For this program, the integer parameter a is a COPY of the variable n1 while the
integer parameter b is a COPY of the variable n2. When the add(...) function is
called, the value of n1 DOES NOT CHANGE because of the passing by value.
33
Cont…
Passing by reference
This method of passing reference is very different
from the first method. Here, values CAN CHANGE if
any of them are being passed by reference.
In order to denote a pass by reference, an
ampersand ( & ) must be placed after the type of the
parameter.
Below is a program that will show an example of a
both a pass by value call and a pass by reference.
34
Cont…
// for loop to print out index
#include <iostream>
#include <conio.h>
Using namespace std;
void dbl(int& a, int& b){
a*= 2;
b*= 2;}
void trip(int a, int b){
a*=3;
b*=3;}
int main(){
int x = 4, y = 6;
cout << "AT START:" << endl;
cout << "x= " << x << " y= " << y << endl;
//call the dbl function:
dbl(x,y);
cout << "AFTER DBL CALL:" << endl;
cout << "x= " << x << " y= " << y << endl;
//call the trip function:
trip(x,y);
cout << "AFTER TRIP CALL:" << endl;
cout << "x= " << x << " y= " << y << endl;}
35
Cont…
This program contains two functions, dbl(...) and trip(...)
which will double and triple a two numbers accordingly
when called. The dbl(...) function contains a pass by
reference, which will change the values of the original
variables, while the trip(...) function contains a pass by
value, which only passes a copy of the values to the
function.
The output of this program is as follows:
AT START:
x=4 y=6
AFTER DBL CALL:
x=8 y=12
AFTER TRIP CALL:
x=8 y=12
36
Scope of variables
Variable scope refers to the region of a program
where a variable is visible and accessible.
In C++, there are primarily two types of variable
scope:
Local variables - are declared within functions or
blocks and have a limited scope within that specific
function or block.
Global variables - are declared outside of any
function or block, making them visible throughout
the entire program.
37
Cont…
local vs global variable
#include <iostream> #include <iostream>
using namespace std; using namespace std;
// Global variable int g = 20;
declaration: int main()
int g = 20; int main() { 10 { 10
// Local variable declaration: int g = 10; 20
int g = 10; cout << g << endl;
cout << g << endl; return cout <<::g << endl;
0; } return 0;
}
38
Inline Functions
An inline function is a function that expanded in line
when it is invoked.
That is the compiler replaces the function call with
#include <iostream.h>
the corresponding function#include<conio.h>
code .
Syntax: int multiply(int);
int main( )
inline function-header { {
int x;
Function body cout<< "\n Enter the Input Value: ";
} cin>>x;
cout<<"\n The Output is: " <<
multiply(x);
getch();
}
inline int multiply(int x1) {
return 5*x1;
}
39
Member Functions
With C++ as many other languages, there are
whats called member functions. They are "pre-
made" by the language that you are using. In
general, they are part of the class it comes from.
All member functions are accessed with the dot
operator ( . )
With the cout class, there are member functions
that control output formatting. Let's see the cout
stream and some of its member functions.
width( numCharacters )
sets the spacing of the output in terms of the number
of characters (the argument). The width is valid only
on the next cout statement. Here is an example:
40
Cont…
#include <iostream>
#include <conio.h>
using namespace std;
int main(){
cout << "Hi!";
cout.width(11);
cout << "Bye!";
getch();
return 0;
}
The width will set 11 spaces for the "Hi!" string. Then, the
"Bye!" string will print with no restriction in terms of size. The
output is:
Hi! Bye!
41
Cont…
fill( character )
sets the character that will be used in output that has a width larger than the expression needs.
Using the example above, let's add another line of code to the program that uses fill:
#include <iostream>
#include <conio.h>
Using namespace std;
int main(){
cout << "Hi!";
cout.width(11);
cout.fill('-');
cout << "Bye!";
getch();
return 0;
}
The fill() function will accept a character as its parameter and will use it to fill the
unused spaces from the string. Here, there are 7 dashes that are used. This is the
output:
Hi!-------Bye!
With the cin class, there are member functions that deal with input. Let's see two of
them.
42
Cont…
get( charArray, capacity )
The cin.get() function will take a line of input and be able to include white
spaces. Until now, the cin stream stops the input at a white space. Now,
with this function and the next, we can control that. Here is an example.
#include <iostream>
#include <conio.h>
Using namespace std;
int main(){
char line[100];
cout << "Please enter a string no more than 100 characters:\n";
cin.get(line, 100);
getch();
return 0;
}
This example will allow a user to enter a string that will include white
spaces. There are 2 arguments that need to be passed to the function. The
first is the name of the character array and the second is the space in that
array.
43
Cont…
getline( charArray, capacity, endingCharacter )
The cin.getline() function will take a line of input and be able to include
white spaces. The only difference between the get() and getline()
functions is that getline() will have a default terminating character of the
newline character '\n'.
#include <iostream>
#include <conio.h>
Using namespace std;
int main(){
char line[100];
cout << "Please enter a string no more than 100 characters:\n";
cin.getline(line, 100, '-');
getch();
return 0;
}
If you need another character other than the newline, you may specify
that as a third parameter, as seen above.
44
Function Overloading
In a C++ program, several functions can have the same name. This is
called function overloading, or overloading a function name. Before we
state the rules to overloading a function, let us define the following:
Two functions are said to have different formal parameter lists if both
functions have:
A different number of formal parameters or
If the number of formal parameters is the same, then the data type of the formal
parameters, in the order you list them, must differ in at least one position.
For example, consider the following function headings:
void functionOne(int x)
void functionTwo(int x, double y)
void functionThree(double y, int x)
int functionFour(char ch, int x, double y)
int functionFive(char ch, int x, string name)
These functions all have different formal parameter lists.
Now consider the following function headings:
void functionSix(int x, double y, char ch)
void functionSeven(int one, double u, char firstCh)
45
Cont…
The functions functionSix and functionSeven both have three formal
parameters, and the data type of the corresponding parameters is the
same. Therefore, these functions have the same formal parameter list.
To overload a function name, any two definitions of the function must have
different formal parameter lists.
Function overloading: Creating several functions with the same name.
The signature of a function consists of the function name and its formal
parameter list. Two functions have different signatures if they have either
different names or different formal parameter lists. (Note that the signature
of a function does not include the return type of the function.)
If a function’s name is overloaded, then all of the functions in the set have
the same name. Therefore, all of the functions in the set have different
signatures if they have different formal parameter lists. Thus, the following
function headings correctly overload the function functionXYZ:
void functionXYZ()
void functionXYZ(int x, double y)
void functionXYZ(double one, int y)
void functionXYZ(int x, double y, char ch)
46
Recursion Function
A function that calls itself is known as a recursive function. And, this
technique is known as recursion.
Working of Recursion in C++ int main()
void recurse() {
{ int num = 5;
#include <iostream> int res = factorial(num);
... .. ... using namespace std; cout << "Factorial of " <<
recurse(); int factorial(int n)
num <<
... .. ... { " is: " << result << endl;
} // Base case }
if (n == 0)
return 1;
int main()
// Recursive case: Factorial of 5 is: 120
{ return n * factorial(n -
... .. ... 1);
recurse(); }
... .. ...
}
47
Cont…
The recursion continues until some condition is met.
To prevent infinite recursion, if...else statement (or similar approach) can be used where one
branch makes the recursive call and the other doesn't.
Example 1: Factorial of a Number Using Recursion
// Factorial of n = 1*2*3*...*n
#include <iostream>
using namespace std;
int factorial(int);
int main() {
int n, result;
cout << "Enter a non-negative number: ";
cin >> n;
result = factorial(n);
cout << "Factorial of " << n << " = " << result;
return 0;}
int factorial(int n) {
if (n > 1) {
return n * factorial(n - 1);
} else {
return 1; }}
48
Cont…
Advantages of C++ Recursion
It makes our code shorter and cleaner.
Recursion is required in problems concerning data
structures and advanced algorithms, such as Graph
and Tree Traversal.
Disadvantages of C++ Recursion
It takes a lot of stack space compared to an iterative
program.
It uses more processor time.
It can be more difficult to debug compared to an
equivalent iterative program.
49
Exercise
1.Write the function larger that is used to
determine the largest number from a set of
numbers. For the purpose of illustration, this
program determines the largest number from a
set of 10 numbers. You can easily enhance this
program to accommodate any set of numbers.
Input :A set of 10 numbers.
Output :The largest of 10 numbers.
Suppose that the input data is:
15 20 7 8 28 21 43 12 35 3
50
51
?