0% found this document useful (0 votes)
6 views47 pages

Chapter 4 Functions

Chapter 4 discusses functions in C++, explaining their importance in code organization and reuse. It categorizes functions into built-in and user-defined types, detailing various forms of user-defined functions based on parameters and return types. The chapter also covers function declaration, definition, calling methods, and introduces concepts like function overloading, overriding, recursion, and iteration.

Uploaded by

peter haile
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)
6 views47 pages

Chapter 4 Functions

Chapter 4 discusses functions in C++, explaining their importance in code organization and reuse. It categorizes functions into built-in and user-defined types, detailing various forms of user-defined functions based on parameters and return types. The chapter also covers function declaration, definition, calling methods, and introduces concepts like function overloading, overriding, recursion, and iteration.

Uploaded by

peter haile
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

CHAPTER 4

Functions in c++
Function in C++

◦A function in C++ is a block of code


that performs a specific task.
◦It allows you to reuse code, organize
programs, and make code easier to
understand.
Types of Functions

◦Built-in functions
◦→ Provided by C++ (e.g., sqrt(), cout,
cin)
◦User-defined functions
◦→ Functions you create yourself.
1. Built-in (Library) Functions

◦These are functions already provided by


C++ libraries.
◦Examples
◦cout (from <iostream>)
◦sqrt() (from <cmath>)
◦strlen() (from <cstring>)
Built-in (Library) Functions
examples
◦ 1. Built-in (Library) Functions
◦ #include <iostream>
◦ #include <cmath>
◦ using namespace std;

◦ int main() {
◦ cout << sqrt(25); // built-in function
◦}
2. User-Defined Functions

◦ These are functions created by the programmer


◦ void greet() {
◦ cout << "Hello!";
◦}
Types of User-Defined Functions
Based on Parameters & Return Type
◦A. Function with no parameters and
no return value
◦void display() {
◦ cout << "No parameters, no return";
◦}
◦B. Function with parameters but no
return value
◦void show(int x) {
cout << "Value: " << x;
}
◦C. Function with no parameters but
returns a value
int getNumber() {
return 10;
}
◦D. Function with parameters and returns
a value
int add(int a, int b) {
return a + b;
}
Function Declaration
&Definition

Declaration Definition
Tells compiler a function
Contains actual code
exists
No body Has a body { }
Does not end with
Ends with semicolon
semicolon
Example: int add(int a,int b)
Example: int add(int,int);
{...}
Declaration
◦int add(int a, int b); // declaration
◦int main() {
◦ cout << "Sum = " << add(5, 3);
◦ return 0;
◦}
Definition
◦int add(int a, int b) { //
definition
◦ return a + b;
◦}
User-Defined Function
Example
Definition
Functions in C++ are a fundamental building blocks of code in a
program that perform a specific task.
They allow code reuse, modularization, and abstraction,
enhancing the readability and maintainability of the code.
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.
You can divide up your code into separate functions.
How you divide up your code among different functions is up to
you, but logically the division usually is such that each function
performs a specific task.
Create a Function
C++ provides some pre-defined functions, such as main(), which is
used to execute code.
But you can also create your own functions to perform certain
actions.
To create (often referred to as declare) a function, specify the name
of the function, followed by parentheses ():
Function Declaration and Definition
A C++ function consist of two parts:
Declaration: the return type, the name of the function, and parameters (if any)
A function declaration tells the compiler about a function's name, return type, and
parameters.
Definition: the body of the function (code to be executed)
A function definition provides the actual body of the function.
Function Declaration
◦In C++, if you want to define the function after the main function,
then you have to declare that function first.
◦A function declaration tells the compiler about the number of
parameters, data types of parameters, and returns type of
function.
◦Writing parameter names in the function declaration is optional but it
is necessary to put them in the definition.
◦The syntax for a function declaration is:
o return_type function_name(parameter_list);
Function Declaration
◦The return type is the data type of the value that the
function will return when it is executed.
◦Then there is the function name, followed by the
parameters which are not mandatory, which means a
function may or may not contain parameters.
◦In most programming languages, every function has a
return type, even if it's implicitly defined.
◦The return type specifies the kind of data that the
function will produce as output when it is called.
Function Definition
◦ A function declaration introduces the function name and its type.
◦ It associates the function name/type with the function body.
◦ Definition specifies the body for a function, associates an identifier with the function,
and allocates storage for it.
◦ A function definition specifies the body of the function.
Function Definition
Ø 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, 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.
Ø Function Body − The function body contains a collection of statements that define what the
function does.
How to Call a Function in C++
◦ To call a function in C++, you need to provide the name of the function, along with any
necessary arguments or parameters.
◦ The syntax for calling a function is:
◦ function_name(argument1, argument2, ..., argumentN);
◦ function_name is the name of the function you want to call, and argument1,
argument2, ..., argumentN are any inputs or parameters that the function takes.
◦ If the function takes no parameters, you can simply use an empty pair of parentheses
after the function name.
◦ Function Declaration and Definition
o Declaration
 // Function declaration (prototype)
 void functionName(int arg1, float arg2);
o Definition
 Function definition

 void functionName(int arg1, float arg2) {


// Function body
// Code to perform the task
}
Class Work
Write a function that takes two integers as parameters and returns their sum.
Write a function that takes two doubles as parameters and returns their product.
Write a function that takes two integers as parameters and returns the maximum of the
two.
Write a function that takes two integers as parameters
and returns their sum.
Write a function that takes two integers as parameters and returns the maximum of the
two.
Quiz (5%)
◦Write a program to print the sum of two numbers entered by user by defining your
own function.
◦Write a program to print the circumference and area of a circle of radius entered
by user by defining your own function.
◦Define a program to find out whether a given number is even or odd using
function.
◦Write a program to find the factorial of a given number by using a function in C++
programming language.
Factorial by Function
Types of functions
There are two types of function:
o 1.Standard Library Functions: Predefined in C++
o 2.User-defined Function: Created by users

•Library functions perform specific tasks and are ready to use without the need for explicit
implementation by the programmer.
•Examples include functions for mathematical operations (sqrt, sin, cos), input/output
operations (cout, cin), string manipulation (strlen, strcpy), and many others.
•Library functions save time and effort by providing commonly used functionalities that
programmers can leverage in their programs.
Different Types of User-defined Functions in C++

◦A user-defined function is one that is defined by the user when writing


any program, as we do not have library functions that have predefined
definitions.
◦To meet the specific requirements of the user, the user has to develop his
or her own functions.
◦Such functions must be defined properly by the user.
◦There are four types of user-defined functions divided on the basis of
arguments they accept and the value they return:
o1.Function with no arguments and no return value
o2.Function with no arguments and a return value
o3.Function with arguments and no return value
o4.Function with arguments and with return value
Function with No Arguments and No Return
Value
◦ Functions that have no arguments and no return values can either be used to display
information or to perform any task on global variables.
◦ In this type, as the name suggests, it passes no arguments to the function, and you print
the output within the function. So, there is no return value.

void sum()
{
int x, y;
cout<<"Enter x and y\n";
cin>>x>>y;
cout<<"Sum of x and y is: “<<x
+ y;
}
Function with No Arguments and With Return Value

◦ Functions that have no arguments but have some return values are used to perform
specific operations and return their value. In this type, it passes no arguments to the
function, but there is a return value.

int sum()
{
int x, y, s = 0;
cout<<"Enter x and y\n";
cin>>x>>y;
s = x + y;
return s;
}
Function With Arguments and No Return Value
◦ Functions that have arguments but no return values. Such functions are used to display
or perform some operations on given arguments.
◦ In this type of function, it passes arguments, but there is no return value. And it prints
the output within the function.

void sum(int x, int y)


{
cout<<Sum of x and y is: “<<x + y;
}
Function With Arguments and With Return
Value
◦ Functions that have arguments and some return value. These functions are used to
perform specific operations on the given arguments and return their values to the user.
◦ In this type of function, it passes arguments, and there is also a return value.

int sum(int x, int y)


{
return x + y;
}
Function Pass
◦ Several ways exist in which data (or variables) could be sent as an argument to a
function.
◦ Two of the common ones are Passing by Value and Passing by Reference.
◦ Passing by reference allows a function to modify a variable without creating a copy.
◦ We have to declare reference variables.
◦ The memory location of the passed variable and parameter is the same.
◦ Therefore, any change to the parameter also reflects in the variable inside its parent
function.
Function Call By Value
◦ A function is a collection of statements that accept inputs, carry out certain
calculations, and output the results.
◦ The concept is to group similar or often performed actions into a function so that we
may call the function rather than writing the same code again for various inputs.
◦ A function is a section of code that executes only when it is called.
◦Pass by value means that a copy of
the actual parameter’s value is
made in memory, i.e. the caller and
callee have two independent
variables with the same value.
◦If the callee modifies the parameter
value, the effect is not visible to the
caller.
1.Passes an argument by value.
2.Callee does not have any access to
the underlying element in the calling
code.
3.A copy of the data is sent to the
callee.
4.Changes made to the passed
variable do not affect the actual
Pass by reference
◦ Pass by reference (also called pass by address)
means to pass the reference of an argument in the
calling function to the corresponding formal
parameter of the called function so that a copy of the
address of the actual parameter is made in memory,
i.e. the caller and the callee use the same variable
for the parameter. If the callee modifies the
parameter variable, the effect is visible to the caller’s
variable.
◦ Overview:
1.Passes an argument by reference.
2.Callee gives a direct reference to the programming
element in the calling code.
3.The memory address of the stored data is passed.
4.Changes to the value have an effect on the original
data.
Assignment –Presentation
(10%)
◦ Function call by value and by reference- Theory
◦ Write a c++ function that Swap two numbers using Pass-By-Reference and
pass by value
Function overloading and function overriding
◦ Function overloading and function overriding are two important concepts in C++ that
involve the use of functions in classes and inheritance. Here's an explanation of each:
◦ Function Overloading:
◦ Function overloading refers to the ability to define multiple functions in the same scope
(either within a class or a namespace) with the same name but different parameter lists.
◦ The compiler determines which version of the function to call based on the number and
types of arguments passed to it.
Example of Function
Overloading:

In the above example, the add function is overloaded to accept different numbers
of parameters.
Function Overriding:
◦ Function overriding occurs when a derived class provides a specific implementation
of a method that is already defined in its base class.
◦ The function signature (name and parameters) in the derived class must match
exactly with the function signature in the base class for overriding to occur.
◦ Function overriding is a feature of inheritance and is used to achieve runtime
polymorphism.
Example of Function Overriding:

In this example, the makeSound function in the Dog class overrides the makeSound
function in the Animal class.
The keyword override is used to explicitly indicate that the function is intended to
override a base class function.
Recursive and Iterative
Functions
• Recursive: Recursion is a programming technique where a function calls itself directly
or indirectly to solve a problem.
• Recursive functions break down a problem into smaller, similar subproblems and solve
each subproblem recursively.
• Recursion uses the call stack to manage function calls and track state, which can lead
to stack overflow errors if not carefully implemented.
• Recursive solutions are often elegant and concise, especially for problems with
recursive structure like tree traversal, factorial calculation, and Fibonacci sequence
generation.
• Recursion is commonly used for tasks that can be naturally expressed in terms of self-
similarity or when the problem is inherently recursive.
◦ Iterative Functions:
◦ Iteration is a programming technique where a loop structure (e.g., for, while, do-
while) is used to repeatedly execute a block of code until a condition is met.
◦ Iterative functions use loop constructs to iterate through a sequence of steps or
calculations, often updating mutable variables in each iteration.
◦ Iteration is generally more efficient in terms of memory usage and execution time
compared to recursion, as it avoids the overhead of function calls and maintaining
the call stack.
◦ Iterative solutions are preferred for problems that can be naturally expressed using
loops and do not require the overhead of recursion, especially when performance is
critical.
Example
◦ Write C++ program to find factorial of given number
Comparison
Property Recursion Iteration

Definition Function calls itself. A set of instructions repeatedly executed.

Application For functions. For loops.

Through base case, where there will be no When the termination condition for the
Termination function call. iterator ceases to be satisfied.

Used when code size needs to be small, and Used when time complexity needs to be
Usage time complexity is not an issue. balanced against an expanded code size.

Code Size Smaller code size Larger Code Size.

Recursion uses more memory as compared Iteration uses less memory as compared to
Memory to iteration. recursion.
If the recursive function does not meet to a If the control condition of the iteration
termination condition or the base case is statement never becomes false or the
Infinite not defined or is never reached then it leads control variable does not reach the
Repetition to a stack overflow error and there is a termination value, then it will cause infinite
chance that the an system may crash in loop. On the infinite loop, it uses the CPU
infinite recursion. cycles again and again.
Exercises
Write a function that takes an integer as a parameter and returns its factorial.
Write a function that takes a double base and an integer exponent as
parameters and returns the result of base raised to the power of exponent.
Write a function that takes a string name as a parameter and prints a greeting
message.
Write a function that takes a string as a parameter and returns true if it's a
palindrome (reads the same forwards and backwards), false otherwise.
Write a function that takes an integer year as a parameter and returns true if
it's a leap year, false otherwise.
Write a function that takes an integer as a parameter and returns true if it's a
prime number, false otherwise.
Write a function that takes an integer n as a parameter and prints the first n
Fibonacci numbers.

You might also like