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

Chapter 1 Function (1)

Uploaded by

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

Chapter 1 Function (1)

Uploaded by

Mintesnot Geta
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 57

Chapter one

1. Functions
4.1. What is a function?
♣ Functions are the main part of top-down structured programming. Therefore, a
function is a block of code designed to tackle a specific problem.
♣ A function is a set of statements that take inputs, do some specific
computation, and produce output.
♣ The idea is to put some commonly or repeatedly done tasks together and make
a function so that instead of writing the same code again and again for different
inputs, we can call the function.
♣ In simple terms, a function is a block of code that only runs when it is called.
Advantages of Function
Creating functions in a program is beneficial in:

I. Avoid repetition of codes.

II. Increase program readability.

III. Divide a complex problem into many simpler problems.

IV. Reduce chances of error.

V. Makes modifying a program becomes easier.


4.2. Declaring, defining and calling functions
A function usually has three components.
They are:
1.Function declaration
2.Function definition
3.Function call
1. Function Declarations

declaring a function before calling a function is called function declaration or


prototype.
Function declaration informs the compiler about the function’s name, type
and number of argument it receives and type of value it returns
A function declaration has the following syntax:

return_type function_name( parameter list );


Cont…
♣ The function return type: This specifies the type of value the function returns.
♣ A function which returns nothing should have a return type void.
♣ The function name: this is simply a unique identifier
♣ The function parameters: it is also called its signature. This is a set of zero
or more typed identifiers used for passing values to and from the function.
Example: int max(int num1, int num2);

♣ Parameter names are not important in function declaration only their type is
required, so following is also valid declaration
Example int max(int, int);
Example function declaration cont…

void display(char);
/*function name = display, receives a character as
argument and returns nothing*/
int sum(int,int);
/*function name = sum, receives two integers
as argument and returns an integer*/
function declaration Cont…
The function prototype is the template of the function which tells the details
of the function.
Some examples of acceptable and not acceptable prototypes are shown
below:
♣ int sum(int a, int b); //Acceptable

♣ int sum(int a, b); // Not Acceptable

♣ int sum(int, int); //Acceptable


2. Defining a function

♣ A function definition consists of two parts: interface (prototype) & body.


♣ The brace of a function contains the computational steps (statements) that computerize the
function.
♣ 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.
Syntax for function definition
returntype function_name ([arguments])
{
statement(s);
... ... ...
}
3. Calling the function

♣ Using a function involves ‘calling’ it.


♣ Calling a function means making the instruction of the function to be executed.
♣ A function call consists of the function name followed by the call operator brackets ‘()’,
inside which zero or more comma-separated arguments appear.
♣ The number and type of arguments should match the number of function parameters.
♣ Each argument is an expression whose type should match the type of the corresponding
parameter in the function interface.
♣ Function call statement calls the function by matching its name and arguments.
♣ A function call can be made by using function name and providing the required
parameters.
3. Calling the function cont…

Syntax for function call


function_name ([actual arguments]);
Example 1:function components
#include <iostream>
using namespace std;
int addFunc(int, int);
int main() {
int x, y, sum;
cout << "Enter two numbers: ";
cin >> x >> y;
sum = addFunc(x, y);
cout<<"The sum of "<<x<<" and " <<y<<“is:
"<<sum;
return 0;
}
int addFunc(int num1, int num2) {
int addFunc;
addFunc = num1 + num2;
return addFunc;
}
4.4. Global versus local variables
♣ A scope is a region of the program and broadly speaking there are two places,
where variables can be declared and which determines where a name can be
accessed - global and local
♣ Variables are classified into Global variables and Local variables based on
their scope.
♣ Inside a function or a block which is called local variables.
♣ Outside of all functions which are called global variables.
♣ The local variable is declared inside a function, whereas
♣ the Global variable is declared outside the function.
4.4. Global versus local variables cont…
♣ Global variables are visible and available to all statements in a setup script that follow its
declaration.
♣ A variable is local if it is declared between the function declaration and the keyword
begin within that function.
♣ Local variables are visible and available only within the function where they are declared.
♣ A variable defined inside a function (defined inside function body between braces) is
called a local variable or automatic variable.
♣ Its scope is only limited to the function where it is defined.
♣ In simple terms, local variable exists and can be accessed only inside a function.
♣ The life of a local variable ends (It is destroyed) when the function exits.
4.4. Global versus local variables

#include <iostream>
using namespace std;
int g; // Global variable declaration:
int main () {
int a, b; // Local variable declaration:
a = 10; // actual initialization
b = 20;
g = a + b;
cout << g;
return 0;
}
Function Parameters and arguments
♣ The difference between parameters and arguments:
♣ Function parameters are the names listed in the function's definition.
♣ The parameter is referred to as the variables that are defined during a function
declaration or definition.
♣ These variables are used to receive the arguments that are passed during a function
call.
♣ Function arguments are the real values passed to the function.
♣ Parameter is the variable in the declaration of the function.
♣ An Argument is referred to the values that are passed within a function when the function
called.
Function Parameters and arguments cont…
♣ Parameter → placeholder (This means a placeholder belongs to the function
naming and be used in the function body)
♣ Argument → actual value (This means an actual value which is passed by
the function calling)
A parameter is a variable in a function definition. It is a placeholder and
hence does not have a concrete value.
An argument is a value passed during function invocation.
Function Parameters and arguments example
#include <iostream>
using namespace std;
void introduction(string name, int age) // Here name and age are parameters of
the introduction function
{
cout << "Hello! My name is " << name << " and I am " << age <<" years
old."<< endl;
}
int main() {
// Here Jerry and 15 are arguments passed to the introduction function
introduction("Jerry", 15);
return 0;
}
Function Parameters and arguments example
#include <iostream>
using namespace std; Output
// sum: Function definition The summation is 30
int sum(int a, int b)
// returning the addition
return a + b;
}
int main()
{
int num1 = 10, num2 = 20, res;
// sum() is called with
// num1 & num2 as ARGUMENTS.
res = sum(num1, num2);
// Displaying the result
cout << "The summation is " << res;
return 0;
}
Function Parameters and arguments
Passing parameters reading assignment

There are two methods using which we can pass parameters to


a function. These are
Pass by value and
Pass by reference
Passing by value:
♣ A value parameter receives a copy of only the value of the argument passed to it.
♣ As a result, if the function makes any changes to the parameters, this will not affect the
argument.
Passing by Reference
♣ A reference parameter, on the other hand, receives the argument passed to it
and works on it directly.
♣ Any change made by the function to a reference parameter is in effect directly
applied to the argument.
♣ Passing parameters in this way is called pass-by-reference.
4.5. Scope resolution Operator (::)
♣ The scope resolution operator (:: ) is used for several reasons.
If the global variable name is same as local variable name, the
scope resolution operator will be used to call the global variable.
Program to demonstrate the standard namespace using
the scope resolution (::) operator
4.5. Scope resolution Operator (::) cont…
#include <iostream>
Output
using namespace std;
Here is the output
char a = 'm';
The static variable : 50
static int b = 50;
The local variable : s
int main() { The global variable : m
char a = 's';
cout << "The static variable : "<< ::b;
cout << "\nThe local variable : " << a;
cout << "\nThe global variable : " << ::a;
return 0;
}
4.5. Scope resolution Operator (::) cont…
Program to demonstrate the standard namespace using the scope resolution
(::) operator.
#include <iostream>
int main ()
{
int num = 0;
// use scope resolution operator with std namespace
std :: cout << " Enter the value of num: ";
std::cin >> num;
std:: cout << " The value of num is: " << num;
}
Automatic versus static
variables
Automatic variables
storage duration, which determines when a variable is
created and destroyed - static and auto.
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.
Eg. The two statements after main()’s opening brace declared automatic local
variables:
Main{
int i;
auto float x; … }
Automatic variables cont…

The all local variables which are defined within the function are

known as auto (automatic) variables unless not specified i.e. by

default a local variable is an auto variable.

There is no need to put the keyword auto (it's an optional) while

declaring a local variable.


Automatic variables example
#include<iostream>
Using namespace std;
int main() Output
{ a=10, b=20
int a;
auto int b;
a=10; b=20;
cout<<“a=”<<a<<“b=”<<b<<endl;
return 0;
}
Note: Here, a and b both are automatic (auto) variables.
static variables
static variables
The opposite of an automatic is a static variable.
All global variables are static, 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 when you define it.
A local variable is referred to as static when it is declared with the static
keyword.
Syntax of static variables
static data_type variable_name = initial_value;
static local variables
Static variables can be declared and initialized within the function, but the
initialization will be executed only once during the first call.
If static variables are not declared explicitly, they will be declared to 0(zero)
automatically.
Eg. void my_fun()
{ static int num;
static int count = 2;
count=count*5;
num=num+4;
}
static local variables
In the above example:
During the first call of the function my_fun(), the static variable count will be
initialized to 2 and will be multiplied by 5 at line three to have the value 10.
During the second call of the same function count will have 10 and will be
multiplied by 5.
During the first call of the function my_fun(), the static variable num will be
initialized to 0 (as it is not explicitly initialized) and 4 will be added to it at line
four to have the value 4.
During the second call of the same function num will have 4 and 4 will be add
to it again.
N.B. if local variables are static, their values remain in case the function is
called again.
static local variables
Using the static keyword on a local variable changes its duration from automatic
duration to static duration.
This means the variable is now created at the start of the program, and destroyed at the end
of the program (just like a global variable).
As a result, the static variable will retain its value even after it goes out of scope!
Automatic
A variable declared inside a function or as a parameter to a function is automatic by default.
Automatic variables are temporary and are destroyed when the function exits. For
example, if a function is called multiple times, the automatic variables will be freshly
allocated each time.
Static
A variable declared with the keyword static within a function is a static variable.
Static variables remain allocated for the entire program runtime and maintain their value
between function calls.
static local variables
#include <iostream>
using namespace std; Output
void test() 1
{ 2
// var is a static variable
static int var = 0;
++var;
cout << var << endl;
}
int main()
{
test();
test();
return 0;
#include <iostream>
using namespace std;
void demo() {
int autoVar = 0; // Automatic variable
static int staticVar = 0; // Static variable
autoVar++;
staticVar++;
cout << "Automatic Variable: " << autoVar << ", Static Variable: " << staticVar << endl;
} Output
int main() { Automatic Variable: 1, Static Variable: 1
demo(); Automatic Variable: 1, Static Variable: 2
demo(); Automatic Variable: 1, Static Variable: 3
demo();
return 0;
}
autoVar is re-initialized to 0 each time demo() is called, while
staticVar retains its value between function calls.
Static variables are not automatically destroyed at the end of their
scope; they persist for the lifetime of the program.
#include <iostream>
void Print()
{
Output
static int value = 1;
++value;
std::cout<< value << '\n';
}
int main()
{
Print();
Print();
Print();
return 0;
}
Overloaded Functions
♣ Function overloading is a feature of object-oriented programming where
two or more functions can have the same name but different parameters.
♣ When a function name is overloaded with different jobs it is called Function
Overloading.
♣ Functions with the same name are called overloaded functions.
♣ C++ requires that each overloaded functions differ in its argument list.
♣ Overloaded functions enable you to have similar functions that work on
different types of data.
Overloaded Functions
♣ Function overloading or method overloading is the ability to create
multiple functions of the same name with different implementations.
♣ With function overloading, multiple functions can have the same name with
different parameters:
♣ The function overloading in the c++ feature is used to improve the
readability of the code.
♣ It is used so that the programmer does not have to remember various function
names.
Overloaded Functions cont…
Rules of Function Overloading in C++
Different parameters or three different conditions :
1. These functions have different parameter type
sum(int a, int b)
sum(double a, double b)
2. These functions have a different number of parameters
sum(int a, int b)
sum(int a, int b, int c)
3. These functions have a different sequence of parameters
sum(int a, double b)
sum(double a, int b)
Overloaded Functions cont…
N.B:
if two or more functions differ only in their return types, C++ can’t overload them.
Two or more functions that differ only in their return types must have different names
and can’t be overloaded.
Overloaded Functions cont…
1. functions have different parameter type example
#include <iostream>
using namespace std;
void add(int a, int b)
{ Output
cout << "sum = " << (a + b); sum = 12
}
void add(double a, double b)
sum = 11.5
{
cout << endl << "sum = " << (a + b);
}
// Driver code
int main()
{
add(10, 2);
add(5.3, 6.2);
return 0;
}
Overloaded Functions cont…
2. These functions have a different number of parameters
#include <iostream>
using namespace std;
void add(int a, int b)
Output
{
cout << "sum = " << (a + b); sum = 12
} sum = 15
void add(int a, int b, int c)
{
cout << endl << "sum = " << (a + b + c);
}
// Driver code
int main()
{
add(10, 2);
add(5, 6, 4);
return 0;
}
Overloaded Functions cont…
3. These functions have a different sequence of parameters
#include<iostream>
using namespace std;
void add(int a, double b) Output
{
sum = 12.5
cout<<"sum = "<<(a+b);
} sum = 11.5
void add(double a, int b)
{
cout<<endl<<"sum = "<<(a+b);
}
// Driver code
int main()
{
add(10,2.5);
add(5.5,6);
return 0;
}
Overloaded Functions cont…

// same name different parameters


int test() { }
int test(int a) { }
float test(double a) { }
int test(int a, double b) { }
Here, all 4 functions are overloaded functions.
Overloaded Functions cont…
// Error code
int test(int a) { }
double test(int b){ }
Here, both functions have the same name, the same type, and the
same number of parameters. Hence, the compiler will throw an
error.
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.
♣ Recursion may be a bit difficult to understand. The best way to figure out how it works is
to experiment with it.
♣ 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.
♣ The process in which a function calls itself is known as recursion and the corresponding
function is called the recursive function.
♣ The popular example to understand the recursion is factorial function.
Example Recursion function cont…
C++ recursion example: Factorial
#include <iostream>
using namespace std;
int f(int n){
if (n <= 1)
return 1;
else
return n*f(n-1);
}
int main(){
int num;
cout<<"Enter a number: ";
cin>>num;
cout<<"Factorial of entered number: "<<f(num);
return 0;
Example Recursion function cont…
Calculating the Fibonacci sequence
The Fibonacci sequence can be calculated mathematically.
In this approach, each number in the sequence is considered a term, which is represented
by the expression Fn.
The reflects the number's position in the sequence, starting with zero.
n
For example, the sixth term is referred to as F5, and the seventh term is referred to as F6.
Using this numbering, the Fibonacci sequence can be defined by the following three
equations:
F0 = 0 (applies only to the first integer)
F1 = 1 (applies only to the second integer)
Fn = Fn-1 + Fn-2 (applies to all other integers)
Example Recursion function cont…
Term position Fn value Fibonacci number
1st F0 0
2nd F1 1
3rd F2 1
4th F3 2
5th F4 3
6th F5 5
7th F6 8
8th F7 13
9th F8 21
10th F9 34
11th F10 55
12th F11 89
Example Recursion function cont…

The Fibonacci formula is given as:


Fn = Fn-1 + Fn-2, where n > 1.
It is used to generate a term of the sequence by adding its
previous two terms.
C++ Program to Find Fibonacci Numbers using Recursion
#include <iostream> while(i < x) {
using namespace std; cout << " " << fib(i);
int fib(int x) { i++;
if((x==1)||(x==0)) { }
return(x); return 0;
}else { }
return(fib(x-1)+fib(x-2));
}
}
int main() {
int x , i=0;
cout << "Enter the number of terms of series : ";
cin >> x;
cout << "\nFibonnaci Series : ";
Advantages of Recursion function cont..

 Simplicity and Readability


 Efficient for Divide-and-Conquer Algorithms
 Solves difficult issues
 Reduces Code Length
Thank you!!!
Question???
Commet...

You might also like