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

Chapter_Four_Function_and_Passing_Argument_to_Function_All_Part

Chapter Four of the document discusses functions in computer programming, particularly in C++. It covers the definition, declaration, and different methods of passing arguments to functions, including pass by value and pass by reference. The chapter also highlights the importance of modular programming and provides examples of function prototypes, definitions, and parameter passing.

Uploaded by

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

Chapter_Four_Function_and_Passing_Argument_to_Function_All_Part

Chapter Four of the document discusses functions in computer programming, particularly in C++. It covers the definition, declaration, and different methods of passing arguments to functions, including pass by value and pass by reference. The chapter also highlights the importance of modular programming and provides examples of function prototypes, definitions, and parameter passing.

Uploaded by

amanhabtamu32
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Computer

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

3.Passing value of a function by Value

4.Passing value of a function by reference

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

▪ A C++ program might contain more than one function.

▪ 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

▪ If the function doesn’t have a return type- void will be used


▪ void is a reserved word

▪ The function prototype usually placed at the beginning of the program

▪ The definition of the prototype must be given

▪ Many of the built-in functions have their function prototypes already


written in the header files you include in your program by using #include
6
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Defining a Function
▪ The definition tells the compiler how the function works.
▪ Consists of :
1. the function header :
▪ like the function prototype except that the parameters must be named
▪ there is no terminating semicolon
2. its body
▪ the task of the function
▪ Syntax
return_type function_name(parameter declarations)
{
function owned variable declarations;
statements;
}
7
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Defining a Function
▪ E.g.
long Area(long l, long w)
{
return l * w;
}
▪ The return statement without any value is typically used to exit the function early

▪ C++ does not allow nested functions

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

▪ Function ends when reaches right brace


▪ Control goes to caller
9 9
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Execution of Functions / Calling a Function
▪ Function calling refers to invoking or executing a function in a program.
▪ Each function has its own name. When that name is encountered, called function call,
the execution of the program branches to the body of that function – the called
function
▪ To call a function, you need to use its name followed by parentheses "()".
▪ Inside the parentheses, you may pass the required arguments. Calling functions pass
the actual values to parameter lists.
▪ When the function returns, execution resumes on the next line of the calling function
▪ Functions can also call other functions and can even call themselves – recursive
functions 10 10
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Function Components

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

// square function definition returns square of an integer


int square( int y ) // y is a copy of argument to function Definition of square. y is a copy of
{ the argument passed. Returns y *
y, or y squared.
return y * y; // returns square of y as an int
} // end function square

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(){

float num= 9.66;

cout<<“the value of num is:”<<::num<<endl;

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

▪ The syntax for declaring a static variable is:

▪ static dataType identifier;

▪ E.g. : static int x; //declares x to be a static variable of the type int

▪ Static variables declared within a block are local to the block

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

▪ Arguments can be variables, constants, or expressions that evaluate to the expected


parameter types.
19
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Parameter and Argument: Example
#include <iostream>
▪ The function addNumbers(int a, int
//Function declaration/prototype
void addNumbers(int x, int y); b) has two parameters: a and b.
// Function with two parameters: int a and int b
▪ When the function is called in
void addNumbers(int a, int b) {
int sum = a + b; main() with the arguments 3 and 7,
std::cout << "The sum is: " << sum << std::endl;
these values are passed to the
}
int main() { parameters a and b, respectively.
addNumbers(3, 7); // Calling the function with
arguments 3 and 7
▪ The function then adds the two
return 0; numbers and prints the result.
}
20
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Parameter and Argument: Example
# include <iostream>
float area( float, float ); // prototype of function area()
int main()
{
float x, y, z;
cout <<“ \n Enter the values of length and breadth of the room: ”;
cin >> x >> y;
z = area(x,y); // function invoking
cout << “\n The area of room is: “ << z;
} //end of main() function
float area(float a, float b) // definition of a function
{
float k ;
k = a* b;
return (k);
} // end of area() function definition
Output:
Enter the values of length and breadth of the room: 5.0 5.0
The area of the room is : 25.0
21
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Parameter Passing
▪ Parameter passing refers to how arguments are provided to functions
when they are called.
▪ There are three primary ways to pass parameters to a function:
1. Pass by Value
2. Pass by Reference
3. Pass by Pointer
▪ Each method has different implications on how the function interacts
with the arguments passed to it.
22
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Parameter Passing: Pass by Value
▪ In pass by value, a copy of the argument is passed to the
function. This means any modifications made to the parameter ▪ Output:
inside the function do not affect the original argument outside
the function. Inside function: 6
#include <iostream>
void increment(int x) { Outside function: 5
x = x + 1; // Changes x locally
cout << "Inside function: " << x << endl; ▪ The value of num remains
}
int main() { unchanged in main(),
int num = 5;
increment(num); // Pass by value because increment()
// Original value remains unchanged
cout << "Outside function: " << num << endl; works with a copy of num
return 0;
}
23
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Parameter Passing: Pass by Value
▪ Suppose we wish to write a function that will swap two numeric values. It might look
something like this:
#include <iostream.h>
void swap (float, float);
void swap (float x, float y){
float temp = x;
x = y;
y = temp;
}
int main(){
float a = 10;
float b = 27;
cout << "A= " << a << endl <<"B= " << b << endl;
swap(a,b);
cout << "After swapping..." << endl<< "A= " << a << endl <<"B= " << b << endl;
return 0;
} 24 24
Computer Programming Chapter Four: Function and Passing Argument to Function By: Kibru G.
Parameter Passing: Pass by Value
▪Why didn't the swap take place? After all, the function looks like it should work, but it doesn't
work properly.

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

▪ A recursive function typically has:

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

You might also like