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

Chapter - 3

Uploaded by

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

Chapter - 3

Uploaded by

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

Chapter Three

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

performs a specific task.

o A function declaration tells the compiler about a function's name,

return type, and parameters. A function definition provides the actual

2 body of the function.


Introduction Con’t

o The C++ standard library provides numerous built-in functions

that your program can call.

o For example, function strcat() to concatenate two strings,

function memcpy() to copy one memory location to another


location and many more functions.

o A function is known with various names like a method or a sub-

routine or a procedure etc.


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

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.

3)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.

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

// function returning the max between two numbers

int max(int num1, int num2) {


// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
7 }
Function Declarations

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

 return_type function_name( parameter list );

o For the defined function max(), following is the function declaration

 int max(int num1, int num2);

o Parameter names are not important in function declaration only their type

is required, so following is also valid declaration


 int max(int, int);
8
Calling a Function
o 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.

o When a program calls a function, program control is transferred to the

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.

The formal parameters behave like other local


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

While calling a function, there are three ways that


arguments can be passed to a 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.

This is done by using the assignment


operator and assigning values for the
arguments in the function definition. If a
value for that parameter is not passed when
the function is called, the default given value
is used, but if a value is specified, this default
value is ignored and the passed value is used
instead. Consider the following example
13
Example
#include <iostream> // calling a function to add the
using namespace std; values.
result = sum(a, b);
int sum(int a, int b = 20) { cout << "Total value is :" <<
int result; result << endl;
result = a + b;
// calling a function again as
return (result); follows.
} result = sum(a);
int main () { cout << "Total value is :" <<
// local variable declaration:result << endl;
int a = 100;
int b = 200; return 0;
int result; }

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;

// Function taking multiple parameters or arguments of same data type (int)


void sum(int a, int b, int c) {
cout << "Sum: " << (a + b + c) << endl;
} Output
Sum: 6
int main() {
16sum(1, 2, 3);
return 0;
Con’t
2. Multiple Data Types for Multiple Parameters
Functions where parameters can have different
data types.
#include <iostream>
Exampleusing namespace std;

// Function taking arguments of different


data types
void getInfo(string name, int age, double
height) {
cout << name << " is " << age << "
years old and " << height << " meters
tall." << endl;
}
Output
Abebe is 26 years old and 1.78
int main() {
17
meters tall.
getInfo(“Abebe", 26, 1.78);
Kebede is 32 years old and 1.65
Multiple Parameters Passing
Techniques
Multiple parameter techniques define how the
data is transferred and manipulated within the
function. Some of the techniques used are:
Pass by Value
In pass by value, a copy of the actual
parameter’s value is passed to the function.
The changes made to the parameter inside the
function do not affect the original argument.
It is safe and straightforward but can be
inefficient for large data structures due to
copying.

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;
}
}

// Adding two floating-point numbers (Function


definition 3)

26
Thank You!!!
Any ????

27

You might also like