Chapter - 3
Chapter - 3
C++ Function
1
Introduction
o 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.
o You can divide up your code into separate functions and each function
a function body.
4
Cont…
Function consists of the following components
1)Return Type
o A function may return a value.
o The return_type is the data type of the value the function
returns.
o Some functions perform the desired operations without
returning a value. In this case, the return_type is the
keyword void.
5
Cont...
2)Function Name − This is the actual name of the
function. The function name and the parameter list
together constitute the function signature.
4)
6
Function Body − The function body contains a
collection of statements that define what the
Example
o Following is the source code for a function called max(). This function
takes two parameters num1 and num2 and return the biggest of both
o 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.
o A function declaration has the following parts
o Parameter names are not important in function declaration only their type
has to do. To use a function, you will have to call or invoke that function.
called function. A called function performs defined task and when it’s
return statement is executed or when its function-ending closing brace is
reached, it returns program control back to the main program.
o 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
9 returned value.
For example
// calling a function to get max
#include <iostream>
value.
using namespace std;
ret = max(a, b);
// function declaration
cout << "Max value is : " <<
int max(int num1, int
ret << endl;
num2); return 0;
}
int main () { // function returning the max
// local variable between two numbers
declaration: int max(int num1, int num2) {
int a = 100; // local variable declaration
int b = 200; int result;
int ret;
if (num1 > num2)
result = num1;
Output//Max value is : 200 else
result = num2;
10 return result; }
Function Arguments
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.
11
Con’t
1. Call by Value
o 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. By default, C++ uses call by value to
pass arguments.
2. Call by Pointer
o This method copies the address of an argument into the formal parameter.
Inside the function, the address is used to access the actual argument used in
the call. This means that changes made to the parameter affect the argument.
3. Call by Reference
o 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
12 the call. This means that changes made to the parameter affect the argument.
Default Values for Parameters
When you define a function, you can specify a
default value for each of the last parameters.
This value will be used if the corresponding
argument is left blank when calling to the
function.
Outputs
//
14
Multiple Function Parameters in C++
o C++ multiple function parameters describe the
ability of a function to accept more than one
argument or can say functions with multiple
parameters to perform operations using several
inputs, this feature makes a function to execute
more complex operations by working with
multiple subset of data at once.
Syntax
In C++, you can define a function with multiple
parameters by listing them in the function’s
declaration and definition, separated by commas.
Here is the syntax for multiple parameters
return_type function_name(param1_type
param1_name, param2_type parame2_name, ...);
15
Data Types for Multiple Function
Parameters
There are two types of passing data to multiple
function parameters, as given in the following
1.Single Data Type for Multiple Parameters
Functions where all parameters are of the same
data type.
Example
#include <iostream>
using namespace std;
18
Pass by Reference Con’t
o This method passes a reference to the actual parameter,
allowing the function to modify the original argument.
o The function works with the original data rather than a
copy.
o It is efficient as it avoids copying, but requires careful
handling to avoid unintended modifications.
Mutable Types
o These are types whose instances can be
modified after they are created.
o Lists, dictionaries, and sets are common mutable types.
Immutable Types
o These are types whose instances cannot be
changed after they are created.
o Integers, strings, and tuples are common immutable
types.
19
C++ Recursion (Recursive
Function)
o Recursion is a programming technique where a
function calls itself over again and again with modified
arguments until it reaches its base case, where the
recursion stops.
o It breaks a problem down into smaller, more
manageable sub-problems, recursion allows for
elegant and better solutions to complex problems.
Recursive Function
o A recursive function is a function which is particularly
used for recursion where a function calls itself, either
directly or indirectly, to address a problem. It must
include at least one base case to terminate the
recursion and one recursive case where the function
invokes itself.
20
Con’t
Creating a Recursive Function
o The following syntax is used to implement
a recursive function in C++
21
Example
#include <iostream> int main() {
using namespace std; int positive_number;
cout << "Enter a positive integer: ";
cin >> positive_number;
// Recursive Function to if (positive_number < 0) {
Calculate Factorial cout << "Wrong Input, Factorial is
int factorial(int num) { not Defined for Negative Integer" <<
// Base case endl;
} else {
if (num <= 1) {
cout << "Factorial of " <<
return 1; positive_number << " is " <<
} factorial(positive_number) << endl;
// Recursive case }
return 0;
else {
}
return num * factorial(num -
1);
}
}
22
Recursion Vs. Iteration
Recursion
o is a method where a function calls itself over
again and again with modified arguments until it
reaches its base case which stops the recursion.
o The problems which can be divided into
similar sub-problems or which have natural
recursive patterns such as tree traversal or
combinational tasks and manageable depth.
o When a user needs simple, cleaner and
readable code as it provides clean proper
arranged code.
Examples
Tree and graph traversals, divide-and-conquer
algorithms like quicksort and mergesort, and
23
problems involving backtracking like solving
Iteration Con’t
o involves using loops (such as for, while or do-
while) where it involves repeatedly executing
blocks of code until a certain condition is
met.
o Iterative solutions are generally more
efficient in terms of memory and
execution time and which involves simple
repetition.
o For the problems which require simple
looping because iteration is usually more
straightforward and efficient.
o Iteration is more stable for problems
which require a large number of
24
repetitions, as it doesn't risk stack
Function Overloading in C++
o Function overloading allows you to
define multiple functions with the same
name but different parameters.
o Function overloading is used to achieve
polymorphism which is an important
concept of object-oriented programming
systems.
Syntax for Overloaded Functions
Consider the following two function
declarations having the same name but
different parameters
return_type
25
function_name(parameter1);
return_type
Example
#include<iostream> float addition(float a, float b) {
using namespace std; return a + b;
}
// Adding two integers (Function definition 1)
int main() {
int addition(int a, int b) { cout<<addition(10.5f,
return a + b; 20.3f)<<endl;
} cout<<addition(10, 20, 30)<<
cout<<addition(10, 20)<<end
// Adding three integers (Function definition 2)
int addition(int a, int b, int c) { return 0;
return a + b + c;
}
}
26
Thank You!!!
Any ????
27