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

Function

Uploaded by

Abdi Garoma
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Function

Uploaded by

Abdi Garoma
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Chapter 1

Functions in C++
Chapter out line
 Introduction Recursion
 Definition of functions
 Benefits of using functions Definition of recursion
 Anatomy of a Function Recursive functions
 Syntax for creating a function
 Syntax for calling a function
Base case and recursive
 Function Parameters case
 Default parameters Examples of recursion
 Passing by value
 Passing by reference
Definitions of function
 Functions are self-contained units of code that perform a specific task.
 They are reusable and modular units of code that can be called by other
parts of a program.
 Functions take input arguments, perform operations on the input
arguments, and return a value as output.
A function definition in C++ consists of several parts, including the
function header, function body, return statement, and function call.
 The function header declares the name of the function, the return type of
the function, and the types and names of the input arguments.
 The function body contains the code that performs the task of the
function.
Con…

 The return statement is used to return a value from the


function.
 Thereturn value must match the return type declared in the
function header.
A function call is used to invoke a function, including the
function name and the values of the input arguments.
Benefit of functions
 Functionsallow us to break down a program into smaller, more
manageable pieces.
 Functions can be reused throughout a program, reducing code
duplication and improving readability.
 Functionsmake code easier to debug, as each function can be tested
independently.
 Functions allow us to organize code into modules, improving
maintainability and scalability.
 Functions can make code more abstract, allowing us to focus on the
what, rather than the how, of a program.
 A system can be divided in to module, this modules are called function
Anatomy of functions
 function declaration: A function declaration tells the compiler
about a function's name, return type, and parameters.
 Thisallows the compiler to know what the function looks like
before it is defined.
 Function declarations are typically placed in header files, which
are included in the source code files that use the function.
Function declaration syntax:
return_type function_name (parameter_list);
Cont…
 Function declarations can also include the keyword extern to
indicate that the function is defined in another source code file.
 Thisis useful for large projects where functions are defined in
separate source code files.
Eg. extern int add(int a, int b);
In summery, Declaring functions involves declaring the function's
name, return type, and parameters. It is typically placed in header
files and can include the keyword extern to indicate that the function
is defined in another source code file
Cont…
 Function definition: provides the actual body of the function.
 The function body contains the code that performs the task of the function.
Function definition syntax:
Eg. int addNumber(int a, int b){
return_type function_name (parameter_list) { //boy of function
}
// function body
}
 The return type is the data type of the value that the function returns. This can
be any valid data type in C++, such as int, double, or bool.
 The function name is the name given to the function. This should be a
descriptive name that indicates the purpose of the function.
 The parameter list is a comma-separated list of input arguments to the function.
Each argument consists of a data type and a variable name.
Cont…

 The function body contains the code that performs the task of the
function.
 This code can include variable declarations, control structures (such
as if statements and loops), and other function calls.
 The return statement is used to return a value from the function.
 The value returned by the function must match the return type
specified in the function definition.
Cont..
function invocation
 Function invocation is the process of calling a function in C++.
 The function is executed when it is invoked
Syntax for function invocation: function_name(arguments);
 The function name is the name of the function being called.
 The arguments are the values or expressions passed to the function when it is called.
Example of function invocation: int result = add(3, 5);
 In this example, the add() function is being called with arguments 3 and 5.
 The result of the function call is stored in the variable result.
 Functions can also be called without any arguments if they don't require any input values.
 Example function invocation without arguments: print_hello();
 The order of the arguments in the function call must match the order
of the parameters in the function definition.
 Ifthe arguments are not of the correct data type, a compiler error
will occur.
 Example of a compiler error caused by incorrect function invocation:
int result = add("3", 5);
 In this example, the first argument is a string ("3"), which is not a
valid data type for the add() function and it will cause a compiler
error.
In Summary, Function invocation is the process of calling a function
in C++. And the function name and arguments must be written in the
correct syntax and order to avoid compiler errors
Con…
Variable scope in a function
 Scope of variable refers to “where the declared variable is
accessible in the program?”
 It
determines ‘how long it is available to your program’ and
where it can be accessed
 Two kind of variables in program
1)Global variables(identifier) – variables declared outside
of every function
2)Local variables(identifier) - variables declared within a
function (or block)
1. Global scope 2. Local scope
 Variables defined outside of any  You can declare variables within the body
function have global scope of the function and that variable is local
 They are available from any function in variables to that particular function
the program, including main()
 Variables declared within a block are
Unary Scope Resolution Operator (::) scoped to that block – Local variable to that
block

Using ::
, one can access any global variable
even if it is over-shadowed  They can be accessed only within that
by a local variable of the same name block and "go out of existence“ when
that block ends
Con…
#include <iostream.h> void myFunction()
void myFunction(); // prototype {
int x = 5, y = 7; // global variables int y = 10; // local variable
int main() cout << "x from myFunction: " << x << "\n";
cout << "y from myFunction: " << y << "\n\
{
n";
cout << "x from main: " << x << "\n"; }
cout << "y from main: " << y << "\n\n"; Output:
myFunction(); x from main: 5
cout << "Back from myFunction!\n\n"; y from main: 7 x from myFunction: 5
cout << "x from main: " << x << "\n"; y from myFunction: 10
Back from myFunction!
cout << "y from main: " << y << "\n";
x from main: 5
return 0; } y from main: 7
Type and component of functions
Type of function
 The C++ function can be classified in to two custom function and standard
function
 A custom function is user defined function and can be created by users or
programmers
 In custom function, every logic is written by programmer
 int addNumber(int a, int b){ int result=a+b; return res;}
 Standard function is built in function which is called from c++ library like
‘cmath’ by including with #include
 The cmath library provides much of the functionality of a scientific calculator.
 The following table contains several built in maths library used in c++
Cont…
Function Components: Parameters and Arguments
 Function parameters are variables that are passed to a function when it is called.
 They provide a way for the caller to pass data to the function.
 Parametersare defined in the function definition and declaration, and their types
and names must be specified.
Eg. int sum(int a, int b) { return a + b; }
 The parameter list can be empty if the function does not require any input.
 Functions can take input arguments, which are values or expressions passed to
the function when it is called (function calling).
 These input arguments are known as function arguments.
 Function arguments are the actual values that are passed to a function when it is called.
 They are passed in the order that they appear in the parameter list.
Eg. int result = sum(2, 3);
Passing parameters to a function
In C++, there are two ways to pass parameters to a function:
 1. by value and 2. by reference.
Passing Parameters by Value
 A copy of the value is made and passed to the function.
 Any changes made to the parameter within the function have no effect on the
original value outside of the function.
 E.g. void add(int a, int b) {
int result = a + b;
cout << "The sum is " << result << endl; }

To call this function, you simply pass in two integer values: add(2, 3); // The sum is
5
In this example, the values 2 and 3 are passed by value to the add() function. A
copy of each value is made, and the function calculates the sum of the two values.
Passing Parameters by Reference:
In this case, we pass a reference to the original value rather than a copy.
Any changes made to the parameter within the function will also affect the original value
outside of the function.
Eg. void increment(int & num) { num++;
cout << "The new value is " << num << endl; }
To call this function, you pass in an integer variable by reference using the & symbol:
int num = 5; increment(num); // The new value is 6
In this example, the variable num is passed by reference to the increment() function.
The function increments the value of num, and the new value 6 is printed out.
Overall, passing parameters by reference allows for more flexibility and efficiency
 when working with larger data types or
 when you need to modify the original value within the function.
Function overloading
With function overloading, multiple functions can have the same name with different parameters
int plusFuncInt(int x, int y) { int plusFunc(int x, int y) {
  return x + y; }   return x + y; }
double plusFuncDouble(double x, double y) { double plusFunc(double x, double y) {
  return x + y; }   return x + y; }

int main() { int main() {


int myNum1 = plusFuncInt(8, 5);   int myNum1 = plusFunc(8, 5);
double myNum2 = plusFuncDouble(4.3, 6.26);   double myNum2 = plusFunc(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
  cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
  cout << "Double: " << myNum2;
return 0; }
Here Instead of defining two functions that   return 0; }
should do the same thing, it is better to overload Overall, function overloading is a powerful
one. In the example at the right side, we overload feature in C++ that can make code more
the plusFunc function to work for both int and modular, flexible, and easier to read.
double data type
Recursion function
Recursion is the technique of making a function call itself.
This technique provides a way to break complicated problems down
into simple problems which are easier to solve.
Eg. Adding two numbers together is easy to do, but adding a range of
numbers is more complicated.
In the following example, recursion is used to add a range of numbers
together by breaking it down into the simple task of adding two
numbers
Recursion function
Example
Here,when the sum() function is called, it adds
int sum(int k) {
parameter k to the sum of all numbers smaller
  if (k > 0) {
than k and returns the result. When k becomes 0,
    return k + sum(k - 1);
the function just returns 0. When running, the
  } else {
program follows these steps:
    return 0; }
} 10 + sum(9)
int main() { 10 + ( 9 + sum(8) )
  int result = sum(10); 10 + ( 9 + ( 8 + sum(7) ) )
  cout << result; ...
  return 0; 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
} 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0

You might also like