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

Chapter Two User Defined Function

Uploaded by

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

Chapter Two User Defined Function

Uploaded by

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

Basic Computer Programming-II

(Using C++)

Chapter Two
Function in C++(User Defined Functions)
Compiled by
Ataklti N.
1
2.1 What is Function in C++?
A function is a block of code that performs a specific task/ used to perform
certain actions.
A function is a group of statements that together perform a task.
Every C++ program has at least one function, which is main().
And these can be called anytime in the main function without typing the
whole code:
Define the code once, and use it many times.
Why Functions?
Functions make the code reusable.
Functions help us in reducing code redundancy.
Functions make the program easier as each small task is divided into a
function.
Functions increase readability, easy for understanding, writing
2 debugging.
Continued…

 A large program maybe divided into suitable small segments and these
segments can be separately compiled, tested and verified.
 So, division of a very large program into manageable smaller functions
or modules.
 The purpose of a function is to receive data, process it and return a
value to the function which has called it.
 The function in C++ language is also known as procedure, subroutine,
method in other programming languages.
3
Continued…
 Some functions return a numeric value to the calling function.
 These are called return type functions.
 If a function does not return a numeric value we call it void
function.
 A programmer should understand how to declare a function,
define a function and call a function.
 The functions which are declared and defined by a programmer
are called user defined functions or programmer defined
functions.
 Besides, C++ Standard Library has a large collection of
4 predefined functions which can also be used by a programmer.
Types of Functions

 There are two types of functions in C++ programming:


 1. Standard Library Functions: are the functions which are
declared in the C++ header files such as ceil(x), cos(x), exp(x),
etc.
 2. User-defined functions: are the functions which are created
by the C++ programmer, so that he/she can use it many times.

5
2.2.1 User Defined Functions
 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).
 The Component of User defined Functions are:-
– Function declaration
– The definition of a function
– Calling functions
6
2.2.2 Function Prototype
 A function prototype comprises type and name of the function
along with list of types of its parameters enclosed in brackets.
 It ends with a semicolon
 Syntax: type identifier (type-of- parameter1, type-of-
parameter2, … type-of- parameter n );
 The prototype conveys the following information to the compiler.
(i) The type of function, i.e. the type of return value.
(ii) Number of parameters of the function.
(iii) Type of each parameter.
(iv) The order in which the arguments would be placed when the
function is called.
7
Continued…
 The names of parameters may or may not be given in the
prototype, however the names are necessary in the head of
function in the function definition.
 For calling the function in the main() or in any other function you
need to mention the name of function followed by arguments
(values of parameters) in parentheses and end the line by a
semicolon.
 Therefore, it is again reminded that data arguments be given in the
same order and type as given in the declaration of function
prototype.
 If this rule is not followed the program will give erroneous results.
8
Continued…

A function returns only one value.


a function is not defined in-side the main() function.
 Functions maybe with empty parameter list.
 The function may also a void type which means
function could not have a return value

9
Continued…

10
2.2.2 C++ User-defined Function Types

 For better understanding of arguments and return in functions,


user-defined functions can be categorised as:
• Function with no argument and no return value
• Function with no argument but return value
• Function with argument but no return value
• Function with argument and return value

11
2.3 Function Arguments
 Passing arguments : An argument is a piece of data that is passed to
the function from a program.
 Passing these arguments can be done in two ways:
 Call by Value: This method 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.
 Call by Reference: This method 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.
12  This means that changes made to the parameter affect the argument.
2.4 Scope of Variables in C++
 Variable Scope is a region in a program where a variable is
declared and used.
 Variables and Storage Classes: The storage class of variables
determines the which parts of the program can access it and how
long it stays in existence.
 Lifetime: The time period between the creation and destruction
of a variable is called its lifetime(or sometimes its duration)
 Visibility: A variable’s visibility or scope describes the part of
the program where the variable is visible.
 The major storage classes are auto/local, register, static and
global.
13
Local Variables

 A variable defined inside a function (defined inside function


body between braces) is called a local variable or automatic
variable.
 Its scope is only limited to the function where it is defined.
 In simple terms, local variable exists and can be accessed only
inside a function.
 The life of a local variable ends (It is destroyed) when the
14 function exits.
Global Variable
 If a variable is defined outside all functions, then it is called a
global variable.
 The scope of a global variable is the whole program.
 This means, It can be used and changed at any part of the
program after its declaration.
 Likewise, its life ends only when the program ends.
 Scope operator(::) use to access global variable if having the
15
same variable name with local variables.
Static Local variable

 A static local variable exists only inside a function where it is


declared (similar to a local variable) but its lifetime starts when
the function is called and ends only when the program ends.
 The main difference between local variable and static variable
is that, the value of static variable persists the end of the
program.

16
2.5 C++ Function Overloading

 In C++, two functions can have the same name if the number
and/or type of arguments passed is different.
 These functions having the same name but different arguments
are known as overloaded functions.
 Note: In C++, many standard library functions are overloaded.
– For example, the sqrt() function can take double ,float, int,
as parameters.
17
2.6 C++ Programming Default Arguments
(Parameters)
 In C++ programming, we can provide default values for function
parameters.
 If a function with default arguments is called without passing
arguments, then the default parameters are used.
 However, if arguments are passed while calling the function, the default
arguments are ignored.
 the defaults must be added from right to left, i.e., a default value to a
particular argument in the middle of argument is not allowed.
 Examples:
 int mul(int i, int j=5, int k=10); // legal
 int mul(int i = 5, int j); // illegal
 int mul(int i=0, int j, int k=10); // illegal
18

2.7 C++ Recursion

• Recursion is the technique of making a function call itself.


• A function that calls itself is known as a recursive function.
• And, this technique is known as recursion.
 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.
19
Advantages of C++ Recursion

• It makes the 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 can be more difficult to debug compared to an equivalent
iterative program.
20
2.8 Inline Functions in C++

 If a function is inline, the compiler places a copy of the code of


that function at each point where the function is called at compile
time.
 C++ provides inline functions to reduce the function call
overhead.
 An inline function is a function that is expanded in line when it is
called.
21
…Continued
 The compiler may not perform inlining in such
circumstances as:

1. If a function contains a loop. (for, while and do-while)

2. If a function contains static variables.

3. If a function is recursive.

4. If a function return type is other than void, and the return


statement doesn’t exist in a function body.
22
5. If a function contains a switch or goto statement.
2.9 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(), abs(),
isdigit(),rand() 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()
23 and abs(), we need to include the header file math.h.
…Continued
1. The variable that are listed in the function's calls are called?

A. Actual parameter
B. Declared parameter
C. Local Variables
D. Global Variables
2.Which of the following function / types of function cannot have default parameters?
A. Member function of class
B. Main function
C. Member function of structure
D. user defined function
24 01/22/25
…Continued
3. Which of the following statement is correct about default arguments?
A. Only one parameter of a function can be a default argument.
B. Minimum one parameter of a function must be a default argument.
C. All the parameters of a function can be default argument.
D. No parameter of a function can be default.
4. Which of the following function declaration using default arguments is correct?
A. int dfa(int x, int y =5, int z=10)
B. int dfa(int x=5, int y =10, int z)
C. int dfa(int x=5, int y, int z=10)

25 D. All are incorrect


…Continued

4. Assume that the random number generating function rand( ), returns


an integer between 1 and 6 (both inclusive).
If you want to simulate the throwing of a die using this random
function, which expression are going to use from the following
alternatives?
A. rand ( ) % 6
B. rand ( ) % 6 + 1
C. rand ( ) % 5 + 1
26
D. None of the above
…Continued

6. Which of the following is the correct syntax of including a


user defined header files in C++?
A. #include <userdefined.h>
B. #include <userdefined>
C. #include “userdefined”
D. #include [userdefined]

27

You might also like