0% found this document useful (0 votes)
8 views

04 CP_lecture-04_C++ Functions in C++

This document covers the concept of functions in C++, including their construction, types, and usage. It explains predefined library functions and user-defined functions, detailing how to declare, define, and call functions, as well as the differences between passing arguments by value and by reference. Additionally, it introduces function overloading and default arguments, providing examples to illustrate these concepts.

Uploaded by

onetechet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

04 CP_lecture-04_C++ Functions in C++

This document covers the concept of functions in C++, including their construction, types, and usage. It explains predefined library functions and user-defined functions, detailing how to declare, define, and call functions, as well as the differences between passing arguments by value and by reference. Additionally, it introduces function overloading and default arguments, providing examples to illustrate these concepts.

Uploaded by

onetechet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Computer Programming

Using

Course Code: CoSc 1012

April-2025
Chapter IV
Functions in C++

2
Objectives
To understand how to construct programs modularly from
small pieces called functions.

To introduce the common math functions available in the C++


standard library.

To be able to create new functions.

To understand the mechanisms used to pass information


between functions.

To understand how to write and use functions that call


themselves.

3
Introduction
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.

For large programs, it is not practical (although it is possible) to


put the entire programming instructions into one function. we
must break the problem into manageable pieces.
 Example: 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
4
made by the company itself; others, by different companies.
Cont…
A function is known with various names like a method or a
sub-routine or a procedure etc.

Functions are like building blocks. They divide complicated


programs into manageable pieces to get the following benefits:
 While working on one function, we 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, write it once and use it many times.

 Using functions greatly enhances the program’s readability


5
because it reduces the complexity of the function main
Types of Functions
Depending on whether a function is predefined or created by
programmer, there are two types of function:
 Standard Library functions(Predefined functions)

 User defined functions (Created by users )

In C++, the concept of a function, either predefined or user-


defined, is similar to that of a function in algebra. For example,
every function has a name and, depending on the values
specified by the user, it does some computation.

6
I. Library Functions
Usually called system defined functions. These are available to
anyone who writes a C++ program.

Features of these Functions:


 This saves the programmer’s time from writing own functions.

 They are completely debugged, efficient and always produce a


precise output.

 They contribute to provide clarity to the program because they do


not have to be redefined. They reduce the source code, which
saves time of the programmer.

7
Cont…
 For example this are some of the predefined mathematical
functions pow(x, y), sqrt(x), and floor(x).

 The power function, pow(x, y), calculates xy; For example,


pow(2, 3)= 23 = 8.0 and pow(2.5, 3)= 2.53 = 15.625.

 Because the value of pow(x, y) is of type double, we can say


that the function pow is of type double or that the function
pow returns a value of type double.

 Moreover, x and y are called the parameters (or arguments)


of the function pow. Function pow has two parameters.
8
Cont…
The square root function, sqrt(x), calculates the nonnegative
square root of x for x >= 0.0. For example, sqrt(2.25) is 1.5.
The function sqrt is of type double and has only one parameter.

In C++, predefined functions are organized into separate


libraries. For example, the header file iostream contains I/O
functions, and the header file cmath contains math functions.

9
Cont….
The following table shows some of the commonly used built in
functions

10
Cont…
Example: library function

11
Cont…
Output of the above code is

Enter a number: 9

Square root of 9 = 3

In example above, sqrt() library function is invoked to


calculate the square root of a number. Notice code #include
in the above program. Here, cmath is a header file. The
function definition of sqrt() (body of that function) is written in
that file. You can use all functions defined in cmath when you
include the content of file cmath in this program using
#include
12
Cont…
Assignment: Write at least three predefined functions with
example (the example should be C++ Program). N:B Your
function should be deferent from those described above in this
material.

13
Cont…

14
Cont…

15
II. User Defined Functions:
Because of C++ does not provide every function that you will
ever need and designers cannot possibly know a user’s specific
needs, we must learn how to write our own functions. In this
chapter we discuss in detail about user defined functions.

2.1 Declaration and Defining Functions

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.

A function is knows as with various names like a method or a


sub-routine or a procedure etc. 16
Cont….
User-defined functions in C++ are classified into two categories:
 Value Returning Functions: functions that have a return type.
These functions return a value of a specific data type using the
return statement, which we will explain shortly.

 Void Functions: functions that do not have a return type. These


functions do not use a return statement to return a value.

The general form of a C++ function definition is as follows:

17
Cont…
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 (called), you pass a value to the parameter. This value is
referred to as actual parameter. The parameter list refers to the
type, order, and number of 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. 18
Cont…
2.2 How user-defined-function works in C++ P_Language
Consider the figure below. When a program begins running, the
system calls the main() function, that is, the system starts
executing codes from main() function.
When control of program reaches to function_name() inside
main(), the control of program moves to void function_name(),
all codes inside void function_name() is executed and control of
program moves to code right after function_name() inside
main() as shown in figure bellow.

19
Cont…
Example: C++ program to add two integers. Make a function
add() to add integers and display sum in main() function.

20
Cont..
2.3 Function Prototype(declaration)
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.

If an user-defined function is defined after main() function,


compiler will show error. It is because compiler is unaware of
user-defined function, types of argument passed to function
and return type.

A function declaration has the following parts:

21
Cont…
In C++, function prototype is a declaration of function without
function body to give compiler information about user-defined
function. Function prototype in above example:

We can see that, there is no body of function in prototype. Also


there are only return type of arguments but no arguments. You
can also declare function prototype as below but it's not
necessary to write arguments.

Note: It is not necessary to define prototype if user-defined


function exists before main() function.
22
Cont…
2.4 Function Calling

 While creating a C++ function, you give a definition of what


the function has to do. To use a function, you will have to call
or invoke that function. When a program calls a function,
program control is transferred to the called function.

A called function performs defined task and when its return


statement is executed or when its function-ending closing
brace is reached, it returns program control back to the main
program.

23
Cont…
To execute the codes of function body, the user-defined
function needs to be invoked (called). In the above program,
add(num1,num2); inside main() function calls the user-defined
function. In the above program, user-defined function returns
an integer which is stored in variable add.

To call a function, you simply need to pass the required


parameters along with function name, and if function returns a
value, then you can store returned value.

24
Cont…
Let’s look at the following example:

25
Cont…

26
Cont…
2.5 Passing Arguments to Function

If a function is to use arguments, it must declare variables that


accept the values of the arguments. These variables are called
the formal parameters of the function.

The formal parameters behave like other local variables inside


the function and are created upon entry into the function and
destroyed upon exit.

In programming, argument refers to data this is passed to


function (function definition) while calling function.

27
Cont…
In above example, two variables, num1 and num2 are passed
to function during function call.
These arguments are known as actual arguments. The value of
num1 and num2 are initialized to variables a and b
respectively.
These arguments a and b are called formal arguments. This is
demonstrated below:

28
Cont…
Notes on passing arguments
 The numbers of actual arguments and formals argument should be
same. (Exception: Function Overloading)

 The type of first actual argument should match the type of first
formal argument. Similarly, type of second actual argument should
match the type of second formal argument and so on.

 You may call function without passing any argument. The


number(s) of argument passed to a function depends on how
programmer want to solve the problem.

 In above program, both arguments are of int type. But it's not
necessary to have both arguments of same type. 29
Cont…
Return Statement

A function can return single value to the calling program using


return statement. In the above program, the value of add is
returned from user-defined function to the calling program
using statement below:

30
Cont…
The figure below demonstrates the working of return statement:

31
Cont…
In the above program, the value of add inside user-defined
function is returned to the calling function.

The value is then stored to a variable sum. Notice that, the


variable returned, that is, add is of type int and also sum is of
int type.

Also notice that, the return type of a function is defined in


function declarator int add(int a,int b).

The int before add(int a,int b) means that function should


return a value of type int. If no value is returned to the calling
function then, void should be used.
32
Cont..
2.6 Calling/invoking functions by value and by reference
parameters
While calling a function, there are two ways that arguments can
be passed to a function: Call by value and call by reference.

Call by value: The call by value method of passing arguments


to a function copies the actual value of an argument into the
formal parameter of the function. In this case, changes made to
the parameter inside the function have no effect on the
argument.
N.B: By default, C++ uses call by value to pass arguments. In
general, this means that code within a function cannot alter the
33
Cont…
Consider the function swap() definition as follows:

34
Cont…

Which shows that there is no change in the values though they had been
changed inside the function. 35
Cont…
Call by reference: The call by reference method of passing
arguments to a function copies the reference of an argument
into the formal parameter. Inside the function, the reference is
used to access the actual argument used in the call. This means
that changes made to the parameter affect the passed
argument.

To pass the value by reference, argument reference is passed to


the functions just like any other value. So accordingly you need
to declare the function parameters as reference types as in the
following function swap(), which exchanges the values of the
36
two integer variables pointed to by its arguments.
Cont…
Consider the function swap() definition using call by reference
as follows

37
Cont…

38
Cont….
2.7 C++ User-defined Function Types
For better understanding of arguments and return in functions,
user-defined functions can be categorised as:

1. Function with no argument and no return value

2. Function with no argument but return value

3. Function with argument but no return value

4. Function with argument and return value

N.B: Consider a situation in which you have to check prime


number. This problem is solved below by making user-
defined function in 4 different ways as mentioned above. 39
Cont…
1. Functions with no arguments and no return value:

40
Cont…

41
Cont…
2. Function with no arguments but return value:

42
Cont…

43
Cont…
3. Function with argument but no return value:

44
Cont…

45
Cont…
4. Function with arguments and return value.

46
Cont…
NOTE: All four programs above gives the same output and all
are technically correct program. There is no hard and fast rule
on which method should be chosen. The particular method is
chosen depending upon the situation and how a programmer
want to solve that problem.

47
Function Overloading
In C++ programming, two functions can have same
identifier(name) if either number of arguments or type of
arguments passed to functions are different. These types of
functions having similar name are called overloaded functions.
Example of function overloading

48
Cont…
All 4 functions mentioned above are overloaded function. It
should be noticed that, the return type of all 4 functions is
same,i.e, int. Overloaded function may or may not have
different return type but it should have different
argument(either type of argument or numbers of argument
passed). Two functions shown below are not overloaded
functions because they only have same number of arguments
and arguments in both functions are of type int.
 Both functions has same number of argument and same type of
argument
 Hence, functions mentioned below are not overloaded functions.
49
 Compiler shows error in this case.
Cont…

Example 1: Function Overloading:

50
Cont…

51
Cont…

In above example, function test() is called with integer


argument at first. Then, function test() is called with floating
point argument and finally it is called using two arguments of
type int and float. Although the return type of all these
functions is same, that is, void, it's not mandatory to have
same return type for all overloaded functions. This can be
demonstrated by example below.

52
Cont…
Example 2: Function Overloading: C++ Program to return
absolute value of variable types integer and float using function
overloading

53
Cont…

54
Cont…

In above example, two functions absolute() are


overloaded. Both take single argument but one takes
integer type argument and other takes floating point
type argument. Function absolute() calculates the
absolute value of argument passed and returns it.

55
Default Argument
In C++ programming, you can provide default values for
function parameters. The idea behind default argument is very
simple. If a function is called by passing argument/s, those
arguments are used by the function. But if all argument/s are
not passed while invoking a function then, the default value
passed to arguments are used. Default value/s are passed to
argument/s in function prototype. Working of default argument
is demonstrated in the figure below:

56
Cont…

57
Cont…

58
Cont….
• Example: Default Argument: C++ Program to demonstrate
working of default argument

59
Cont…

In the above program, you can see default value passed to arguments(in function
prototype). At first, display() function is called without passing any arguments. In
this case, default() function used both default arguments. Then, the function is
called using only first argument. In this case, function does not use first default
value passed. Function uses the actual parameter passed as first argument and
takes default value(second value in function prototype) as it's second argument.
When display() is invoked passing both arguments, default arguments are not
used.
Note: The missing argument must be the last argument of the list, that is, if
you are passing only one argument in the above function, it should be the
first argument. 60
Function Recursion
 In many programming languages including C++, it is possible to call a
function from a same function. This function is known as recursive function
and this programming technique is known as recursion.
 To understand recursion, you should have knowledge of two important
aspects:
 In recursion, a function calls itself but you shouldn't assume these two functions
are same function. They are different functions although they have same name.
 Local variables are variables defined inside a function and has scope only inside
that function. In recursion, a function call itself but these two functions are
different functions (You can imagine these functions are function1 and function
2. The local variables inside function1 and function2 are also different and can
only be accessed within that function.
 The C++ programming language supports recursion, i.e., a function to call
itself. But while using recursion, programmers need to be careful to define
an exit condition from the function, otherwise it will go into an infinite loop.
61
Cont…
• Example 1: Consider this example to find factorial of a number
using recursion.

62
Cont…
Explanation: How recursion works

63
Cont…
Suppose user enters 4 which is passed to function factorial().
Here are the steps involved:
 In first factorial() function, test expression inside if statement is
true. The statement return num*factorial(num-1); is executed,
which calls second factorial() function and argument passed is
num-1 which is 3.
 In second factorial() function, test expression inside if statement is
true. The statement return num*factorial(num-1); is executed,
which calls third factorial() function and argument passed is num-1
which is 2.
 In third factorial() function, test expression inside if statement is
true. The statement return num*factorial(num-1); is executed,
which calls fourth factorial() function and argument passed is num-
1 which is 1.

64
Cont…
The fourth factorial() function, test expression inside if statement is
false. The statement return 1; is executed, which returns 1 to third
factorial() function.

The third factorial() function returns 2 to second factorial() function.

The second factorial() function returns 6 to first factorial() function.

Finally, first factorial() function returns 24 to the main() function and


is displayed.

65
Cont…
Example 2: The following example generates the Fibonacci
series for a given number using a recursive function:

66
67

You might also like