Chapter_Four_Function_and_Passing_Argument_to_Function_All_Part
Chapter_Four_Function_and_Passing_Argument_to_Function_All_Part
Programming {
Chapter Four: Function and
Passing Argument to Function
{
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Outline
1.Definition of function
2.Declaration of function
2
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Modularity
▪ Modular programming
▪ Breaking down the design of a program into individual components (modules) that can be
programmed and tested independently
▪ A program divided into several smaller parts which can interact or work together
▪ Modules
▪ Can be written and tested separately
▪ Testing is easier (smaller)
▪ Doesn't need to be retested
▪ Reduces length of program
▪ Hides details (data abstraction)
3
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Functions in C++
▪ Modules in C++ are called functions
▪ A large program maybe divided into suitable small segments and these segments can be
separately compiled, tested and verified. function enhance the reusability of the code.
▪ A function groups a number of statements into a unit and gives it a name.
▪ It is executed when it is called from some point of the programs.
▪ The purpose of a function is to receive data, process it and return a value to the function which has
called it.
▪ Functions may interact using function call
▪ Every C++ program has at least one function, main(), where program execution begins
▪ Functions in C++ come in two varieties: user-defined and built-in: E.g pow(), sqrt(), getch(), etc
4
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Function Declaration/Prototypes
▪ Function declarations are also called prototypes, since they provide a model or
blueprint for the function and it ends with a semicolon(;)
▪ It consists of the function's
▪ return type,
▪ name,
▪ parameter list
▪ Functions must be declared before use/Define the function before it is called
by any other function.
▪ Syntax:
▪ return_type function_name (type [parameterName1], type [ParameterName2] ... );
▪ E.g. long int Area(int, int);
Or
long int Area(int length, int width);
5
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Function Declaration/Prototypes
▪ All functions have a return type – default is int
▪ The definition of one function cannot be included in the body of another function, each
function must be defined separately at the top level within a class, namespace, or globally in
the file
▪ A function definition must agree in return type and parameter list with its prototype
8
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Defining a Function
▪ If the function returns a value, it’s definition should end with a return
statement
▪ The body of the function is always enclosed in braces, even when it consists of
only one statement
▪ return keyword
▪ Returns data, and control goes to function’s caller
▪ If no data to return, use return;
11
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
// Creating and using a programmer-defined function.
#include <iostream.h>
int square( int ); // function prototype Function prototype: specifies data types
of arguments and return values. square
int main() expects an int, and returns an int.
{
// loop 10 times and calculate and output
// square of x each time
for ( int x = 1; x <= 10; x++ )
Parentheses () cause function to be called.
cout << square( x ) << " "; // function call When done, it returns the result.
cout << endl;
return 0; // indicates successful termination
} // end main
1 4 9 16 25 36 49 64 81 100 12
#include <iostream.h> void myFunction()
void myFunction(); // prototype {
int y = 10;
int x = 5, y = 7; cout << "x from myFunction: " << x << "\n";
int main() cout << "y from myFunction: " << y << "\n";
{ }
cout << "x from main: " << x << "\n";
cout << "y from main: " << y << "\n\n"; Output:
x from main: 5
myFunction();
y from main: 7
cout << "Back from myFunction!\n\n";
x from myFunction: 5
cout << "x from main: " << x << "\n"; y from myFunction: 10
cout << "y from main: " << y << "\n"; Back from myFunction!
return 0; x from main: 5
} y from main: 7
13
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Unary Scope Resolution Operator ::
▪ Using ::, one can access any global variable even if it is over-shadowed by a local
variable of the same name.
▪ E.g.
#include <iostream.h>
float num=10.8;
int main(){
return 0;
}
14
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Storage Class and Variables
▪ Storage class determines the period during which an identifier exists in memory
▪Automatic variable - memory is allocated at block entry and deallocated at block exit
▪Local variables in functions or blocks. Auto storage class variables are created only
when the block is active, and disappear when the block or function exits.
▪ Static variable - memory remains allocated as long as the program executes
▪Variables declared outside of any block are static variables
▪Local static variable exists during the whole program executing, i.e., the variable
retains its value between function calls.
▪However, the reference to the variable is local in the function or block
▪By default, variables declared within a block are automatic variables
▪Declare a static variable within a block by using the reserved word static
15
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Static and Automatic Variables (continued)
▪ A static local variable is initialized only once, and its value is preserved
even after the function exits
▪ Their scope is the same as any other local identifier of that block
16
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Static and Automatic Variables (continued)
#include <iostream>
void countCalls() { Output:
static int count = 0; // Initialized only once Function called 1 times
count++; Function called 2 times
std::cout << "Function called " << count << " times" << std::endl; Function called 3 times
}
int main() {
The variable count is initialized only the
countCalls(); // First call first time countCalls() is called.
countCalls(); // Second call It retains its value across all subsequent
countCalls(); // Third call calls to the function and is shared across all
instances of a class or a function
return 0;
}
17 17
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Parameter in C++
▪ In C++, parameters and arguments are two important concepts related to function
calls.
▪ Parameters are placeholders or variables that are defined in the function declaration
or definition to accept input values that a function expects to receive when it is called.
▪ Parameters are used to define the behavior of a function and specify the type and
order of the values that need to be passed.
▪ They act as local variables within the function body, holding the values received from
the arguments.
▪ Parameters are defined in the function signature and are enclosed within the
parentheses following the function name.
18
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Arguments
▪ Arguments are the actual values or expressions that are passed to a function when it is called.
▪ They are the concrete values that correspond to the parameters defined in the function.
▪ Arguments provide the input data that the function operates on.
▪ When a function is called, the arguments are passed within the parentheses following the
function name.
▪ The number, order, and types of the arguments must match the parameters declared in the
function.
▪ x and y, the formal parameters of swap are considered local to swap. Only the values of a
and b (10 and 27) are passed to the swap function.
▪Any changes that take place inside the function, stay there and do not get sent back to the
actual parameters in the calling function. This is to protect our variables from unintentional
modification.
▪For the swap function to work as intended, we need to pass a reference to the location of the
actual parameter so that it can be modified by the function. This is called passing by
reference. 25 25
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Parameter Passing: Pass by Reference
▪ In pass by reference, a reference to the original argument is passed to the function.
This allows the function to directly modify the original variable, because it works with
the actual data rather than a copy.
▪ References are indicated by the & symbol in the parameter list.
▪ If a formal parameter is a reference parameter
It receives the address of the corresponding actual parameter
A reference parameter stores the address of the corresponding actual parameter
▪ During program execution to manipulate the data
The address stored in the reference parameter directs it to the memory space of the
corresponding actual parameter
A reference parameter receives the address of the actual parameter
▪ Reference parameters can:
Pass one or more values from a function
Change the value of the actual parameter
26
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Parameter Passing: Pass by Reference
#include <iostream.h> // Output:
void increment(int &x) // Notice the & symbol
{ After function call: 6
x = x + 1; // Changes the actual value of x
}
int main()
The value of num is changed in
{
int num = 5; main(), because increment() has a
increment(num); // Pass by reference
reference to the original variable
cout << "After function call: " << num << endl;
return 0;
}
27
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Parameter Passing: Pass by Reference
#include <iostream.h>
void swap (float&, float&);
int main()
{
float a = 10;
float b = 27.3;
cout << "A= " << a << endl <<"B= " << b << endl;
swap(a,b);
cout << "After swapping..." << endl << "A= " << a << endl <<"B= " << b << endl;
return 0;
}
void swap (float &x, float &y){
float temp = x;
x = y;
y = temp;
} 28 28
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Default Argument
▪ C++ allows us to call a function without specifying all its arguments. In such cases, the
function assigns a default value to the parameter which does not have a matching
arguments in the function call.
▪ Default values are specified when the function is declared.
▪ A default argument is checked for type at the time of declaration and evaluated at the
time of call.
▪ Trailing arguments can have default values , i.e the defaults must be added from right
to left, i.e., a default value to a particular argument in the middle of argument is not
allowed.
▪ Examples:
int mul(int i, int j=5, int k=10); // legal
int mul(int i = 5, int j); // illegal
int mul(int i=0, int j, int k=10); // illegal
int mul(int i =2, int j=5, int k=10); // legal
29
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Default Argument
30
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Recursive Function
▪ A recursive function in C++ is a function that calls itself during its execution.
▪ This technique is useful when solving problems that can be divided into
smaller sub-problems of the same type.
1. Base Case: A condition that stops the recursion, preventing infinite loops.
2.Recursive Case: A case where the function calls itself to solve a smaller
problem.
31
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Recursive Function
▪ A common example of recursion is calculating the factorial of a number (n!), which is defined as:
▪ n!=n×(n−1)! for n>1
▪ 0!=1
#include <iostream>
int factorial(int n) { // Recursive function to calculate factorial
if (n <= 1) {// Base case: when n is 0 or 1, return 1
return 1; }
return n * factorial(n - 1); } // Recursive case: n * factorial of (n-1)
int main() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
int result = factorial(number); // Calling the recursive function
std::cout << "Factorial of " << number << " is " << result << std::endl;
return 0;
}
32
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Recursive Function
▪ Base Case: The recursion stops when n is less than or equal to 1, returning 1. This
is the termination condition.
▪ Recursive Case: The function keeps calling itself with the value n-1 until it
reaches the base case. Each recursive call calculates the factorial of a smaller
number until the entire calculation is completed.
For example:
▪ For factorial(5), the function calls itself as:
▪ 5 * factorial(4)
▪ 4 * factorial(3)
▪ 3 * factorial(2)
▪ 2 * factorial(1) → returns 1 (base case)
▪ Finally, the results are multiplied as:
5 * 4 * 3 * 2 * 1 = 120
33
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Chapter 4;
}
34