0% found this document useful (0 votes)
2 views33 pages

C++ Functions: Declaration to Recursion

This document provides an overview of C++ functions, including their declaration, definition, parameters, and various types such as overloaded and recursive functions. It explains the concepts of passing by value and reference, as well as the differences between automatic and static variables. Additionally, the document includes examples and exercises related to function usage in C++.

Uploaded by

kertinabekele
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)
2 views33 pages

C++ Functions: Declaration to Recursion

This document provides an overview of C++ functions, including their declaration, definition, parameters, and various types such as overloaded and recursive functions. It explains the concepts of passing by value and reference, as well as the differences between automatic and static variables. Additionally, the document includes examples and exercises related to function usage in C++.

Uploaded by

kertinabekele
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

Programming II

Chapter One

C++ Functions

2024-11-28 Kassahun @2024 1


Contents
• Function declaration, definition…
• Function parameters and arguments
• Pass by value and reference
• Return by value and reference
• Overloaded functions
• Recursive functions

2024-11-28 Kassahun @2024 2


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.

• C++ functions generally adhere to the following rules.

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

2024-11-28 Kassahun @2024 3


Declaring, defining and calling functions
• Declaring function (Prototyping):
✓ Function declarations, also called prototypes, provide a model or blueprint
for the function.
✓ They tell the compiler, “a function that looks like this is coming up later in
the program”
✓ The interface of a function (also called its prototype) specifies how it may be
used. It consists of three entities:
✓ The function return type. This specifies the type of value the function
returns.
✓ The function name. this is simply a unique identifier
✓ The function parameters (also called its signature). This is a set of zero or
more typed identifiers used for passing values to and from the function.
2024-11-28 Kassahun @2024 4
functions 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.
❖ A function declaration has the following parts −
Syntax:

return_type function_name( parameter list );

2024-11-28 Kassahun @2024 5


Defining a function
• A function definition consists of two parts: interface
(prototype) & body.
• The brace of a function contains the computational steps
(statements).
• The definition consists of a line (first line of the definition)
called the declarator.
• If function definition is done before the main function, then
there is no need to put the prototype, otherwise the prototype
should be scripted before the main function starts.

2024-11-28 Kassahun @2024 6


Syntax functions Definition
Defining a Function
✓ Syntax:

ReturnType Function_Name ( parameter1, parameter2, ...)


{ statements }

2024-11-28 Kassahun @2024 7


Calling the function
• Calling a function means making the instruction of the function to be
executed.
• The syntax of the call is very similar to that of the declaration, except that the
return type is not used.
• A function call consists of the function name followed by the call operator
brackets ‘()’, inside which zero or more comma-separated arguments appear.
• When a function call is executed, the arguments are first evaluated and their
resulting values are assigned to the corresponding parameters.
• The function body is then executed. Finally the return value (if any) is passed
to the caller.

2024-11-28 Kassahun @2024 8


Example

2024-11-28 Kassahun @2024 9


Function Parameters and arguments
• A function parameter (formal parameter) is a variable declared in
the function declaration. It is a receiving variable.
• Argument (actual parameter) is a value that is passed to the
function by the caller.
• The arguments of a function calling can be passed either passing by
value or passing by reference
Passing by value:
• A function parameter receives a copy of only the value of the
argument.
• As a result, if the function makes any changes to the parameters,
this will not affect the argument.
2024-11-28 Kassahun @2024 10
Example: passed by values
// function example
#include <iostream>
using namespace std;
int addition (int a, int b)
{
int r;
r=a+b;
return r;
}

int main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z;
return 0;
}
2024-11-28 Kassahun @2024 11
Passing by Reference
• A reference parameter receives the address of the argument.
• The variable itself is passed to the function
• Any change made to a reference parameter directly affects argument.
• In passing by reference, in function declaration the type of each
parameter must be followed by an ampersand sign (&).
• This ampersand specifies that corresponding arguments are to be
passed by reference.

2024-11-28 Kassahun @2024 12


Return by Value and By Reference
Return by Value
• A copy of value is returned to the caller.
Example:
int doubleValue(int x)
{
int value = x * 2;
return value ; // A copy of value will be returned here
} // value goes out of scope here

2024-11-28 Kassahun @2024 13


Return by value…
• When to use return by value:
➢ To return variables declared inside the function
➢ To return arguments that were passed by value
• When not to use return by value:
➢ To return pointer (use return by address)
➢ To return a large struct or class (use return by reference).

2024-11-28 Kassahun @2024 14


Example: pass by reference

• The above function modifies parameters a, b and c, correspondingly, values of x,


y and z is also modified.
• Passing by reference is also an effective way to allow a function to return more
than one value
2024-11-28 Kassahun @2024 15
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.
2024-11-28 Kassahun @2024 16
Example Default Values for Parameters

2024-11-28 Kassahun @2024 17


Global vs local variables
• The scope of variables declared within a function or any other inner
block is only their own function or their own block and can not be
used outside of their block.

2024-11-28 Kassahun @2024 18


Scope Operator
Int num1;
Void fun1(int num1)
• A local scope overrides the global {
scope //…..
}
• The global num1 is inaccessible inside
fun1(), because it is overridden by the
local num1 parameter int num1 = 2;
void fun1(int num1)
• This problem is overcome using the {
scope operator ‘::’ which takes a global //…
num1=33;
entity as argument. cout<<num1; /* the output will be 33 */
cout<<::num1; /*the output will be 2 which is
the global */
if(::num1 != 0)//refers to global num1
//…
2024-11-28 Kassahun @2024
} 19
Scope Operator Example

2024-11-28 Kassahun @2024 20


Overloaded Functions
• Unlike C, C++ lets you have more than one function with the same
name.
• Functions with the same name are called overloaded functions.
• C++ requires that each overloaded functions differs in its argument
list.
• Overloaded functions enable you to have similar functions that work
on different types of data.
• Two functions can have same identifier(name) if either number of
arguments or type of arguments passed to functions are different.
2024-11-28 Kassahun @2024 21
Overloaded Functions
• These types of functions having similar name are called overloaded
functions.
/* Example of function overloading */
int test() { }
int test(int a){ }
int test(double a){ }
int test(int a, double b){ }
• Overloaded function may or may not have different return type but it
should have different argument.
• Functions which differ by only their return type can’t be overloaded
and should have different name.
2024-11-28 Kassahun @2024 22
Overloaded Functions
• Overload example:

2024-11-28 Kassahun @2024 23


Example: Overloading function

2024-11-28 Kassahun @2024 24


Automatic versus static variables
➢ The terms automatic and static describe what happens to local variables when a
function returns to the calling procedure.

➢ By default, all local variables are automatic, meaning that they are erased when
their function ends.

➢ You can designate a variable as automatic by prefixing its definition with the
term auto. main()
{
int i;
auto float x;

}
2024-11-28 Kassahun @2024 25
Automatic versus static variables
➢ The opposite of an automatic is a static variable. All global variables are static
and, as mentioned, all static variables retain their values.

➢Therefore, if a local variable is static, it too retains its value when its function
ends-in case this function is called a second time.

➢ To declare a variable as static, place the static keyword in front of the variable
void my_fun()
when you define it.
{
static int num;
static int count = 2;
count=count*5;
2024-11-28 num=num+4; }
Kassahun @2024 26
Inline functions
➢ The function version has a number of advantages.
• it leads to a more readable program.
• it is reusable

➢ The disadvantage of the function version, however is that


• It’s frequent use can lead to considerable performance penalty due to overheads associated
with calling a function.

➢ The overhead can be avoided by defining Abs as an inline function.


inline int Abs(int n) The "inline" keyword is merely a hint to the
{ compiler or development environment.
Return n > 0 ? n : -n;
}
2024-11-28 Kassahun @2024 27
Recursive function
• A function which calls itself is said to be recursive.
• Recursion is a general programming technique applicable to problems which
can be defined in terms of themselves.
• Example: the factorial problem
int factorial(unsigned int n )
{
return n = = 0 ? 1 : n * factorial(n-1);
}
• A recursive function must have at least one termination condition which can
be satisfied.
• Otherwise, the function will call itself indefinitely until the runtime stack
overflows.
2024-11-28 Kassahun @2024 28
Example factorial with Recursive function

2024-11-28 Kassahun @2024 29


Iterative function
• Both iteration and recursion are based on control structure.

• Iteration uses a repetition structure (such as for, while, do…while) and recursive
uses a selection structure (if, if else or switch).

• A set of instructions repeatedly executed.

• If the control condition of the iteration statement never becomes false or the
control variable does not reach the termination value, then it will cause infinite
loop. On the infinite loop, it uses the CPU cycles again and again.

2024-11-28 Kassahun @2024 30


Example factorial with Iteration

2024-11-28 Kassahun @2024 31


Exercise
1. C++ program for Fibonacci series using recursion and iteration.
2. WAP that display the factorial of a given number using iterative and recursive function.
3. WAP that display the swapping of two number using third variable (use pass by value and
reference).
4. WAP that display the swapping of two number with out third variable.
5. An array is defined to be odd-heavy if it contains at least one odd element and every
element whose value is odd is greater than every even-valued element. So {11, 4, 9, 2, 8} is
odd-heavy because the two odd elements (11 and 9) are greater than all the even elements.
And {11, 4, 9, 2, 3, 10} is not odd-heavy because the even element 10 is greater than the
odd element 9.
6. Write a function called isOddHeavythat accepts an integer array and returns 1 if the array
is odd-heavy; otherwise it returns 0.
7. An array is called centered-15 if some consecutive sequence of elements of the array sum
to 15 and this sequence is preceded and followed by the same number of elements. For
example, {3, 2, 10, 4, 1, 6, 9} is centered-15 because the sequence 10, 4, 1 sums to 15 and
the sequence is preceded by two elements (3, 2) and followed by two elements(6,9).
2024-11-28 Kassahun @2024 32
2024-11-28 Kassahun @2024 33

You might also like