Functions and Introduction to Recursion
Functions and Introduction to Recursion
1
What is Function?
o A function is a group of statements that together perform a
task
o A function is a subprogram that can act on data and return
a value.
o Functions (called methods or procedures in other
programming languages) allow the programmer to
modularize a program by separating its tasks into self-
contained units.
o Every C++ program has at least one function, main()
When your program starts, main() is called
automatically.
main() might call other functions, some of which might
call still others.
Each function has its own name, and when that name is
encountered, the execution of the program branches to
the body of that function. 2
Cont…
• You have used functions in every program you have
written
• Functions come in two varieties:
o user-defined function and
o built-in function
• Built-in functions are part of your compiler package--they
are supplied by the manufacturer for your use.
Example:
pow(),floor(),ceil(),exp(),sqrt(),fabs(),cos(),sin(),tan()…
• Implementing any function in addition to main involves
two steps:
• Declaring and Defining the function
• Calling the function
3
Declaring and Defining Functions
• Using functions in your program requires that you first
declare the function and that you then define the function.
o The declaration tells the compiler the name, return type,
and parameters of the function.
o The definition tells the compiler how the function works
4
Declaring the Function
• There are three ways to declare a function:
– Write your prototype into a file, and then use the
#include directive to include it in your program.
– Write the prototype into the file in which your function
is used.
– Define the function before it is called by any other
function. When you do this, the definition acts as its
own declaration.
5
Cont….
Terminology of a Function
• Let’s look at a simple program with one function, main:
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello world!";
return 0;
}
6
Cont…
• The first line, int main (), is the function header.
– Unlike a statement, the function header is not followed
by a semicolon.
– The function header consists of a return type, a function
name, and an argument list.
– The data type int preceding main is the return type,
main is the function name, and the parentheses, empty
in this example but not always, contains the argument
list.
– A function header always is followed by an open curly
brace, which begins the function body.
– The function body ends with a close curly brace.
7
Cont..
• The function body consists of one or more statements. In
this example, the function body consists of two statements.
– The first statement, that display “ Hello world”
– The last statement, return 0, is a return statement.
• The function body must contain a return statement unless
the return type is void,
• The function header and body together are referred to as
the function definition.
• A function cannot execute until it is first defined. Once
defined, a function executes when it is called.
8
Function Prototypes
• Since execution always starts with main, it seems more logical to place
the main function first
• Example:
#include <iostream>
using namespace std;
int main ()
{
printMessage();
return 0;
}
void printMessage (void)
{
cout << "Hello world!";
}
• This code will not compile. The call in main to printMessage()
will be highlighted, with the compiler error message being
“undeclared identifier.” 9
Cont…
• The reason for this compiler error is that when the
compiler, going from top to bottom in your code,
encounters a function call, it must already know of the
function’s name, return type, and arguments.
• This was not a problem when the printMessage function
was defined above the main function.
• However, when the printMessage function was defined
below the main function, when the compiler encounters
the call in main to printMessage(), it does not yet know of
the printMessage function’s name, return type, and
arguments.
10
Solution for this error
• One solution to this problem is to define all functions above main.
– However, this may make your code difficult to read.
• The solution of preference is to prototype each function, except main,
which does not have to be prototyped since it is required by every
program.
• A prototype has the following format.
return-type function-name(argument type, argument type, . . .);
#include <iostream>
using namespace std;
void printMessage(void);//this is the prototype!
int main ()
{
printMessage();
return 0;
}
void printMessage (void)
{
cout << "Hello world!";
} 11
Cont…
• The prototype is above all function definitions.
– This ensures that the compiler, compiling the code from
top to bottom, will encounter the prototype before any
function.
• The prototype is similar to a function header.
– The primary difference is that it has a semicolon at the
end because it is a statement.
– By contrast, a function header must not be followed by
a semicolon.
12
Cont…
• The prototype does not say what the function does or how it
accomplishes its task.
• The prototype gives the compiler information about the function so
the compiler can verify that the program uses the function correctly.
13
Defining the Function
14
Calling a Function
• Unless the printMessage function is called, it is the
programming equivalent of the tree that falls in the forest
without anyone seeing or hearing it; it is there in the
program, but it doesn’t do anything.
• The printMessage function is called in main with the line:
printMessage();
printMessage is the called function, since it is the function
being called from main.
15
Execution of Functions
• The order of execution is as follows:
o Execution always starts with the main function.
o The first statement in main, printMessage(), is executed.
o Execution next shifts to the printMessage function, and
begins with the first statement in that function, which
outputs “Hello world!”
o After the printMessage function completes executing,
execution returns to the main function with the next
unexecuted statement, return 0, which completes the
main function.
16
Cont…
• Order of execution graphically :
17
Scope of variables
• A variable has scope, which determines how long it is
available to your program and where it can be accessed.
• In programs where the only function is main, those variables
can be accessed throughout the entire program ,since main is
the entire program.
• However, once we start dividing up the code into separate
functions , issues arise concerning variable scope and lifetime.
• There are two scopes Local and Global.
18
Local Variables
• Variables declared in function or blocks-body of function
• Not accessible outside function
• This is named local variables, because they exist only locally
within the function itself.
• When the function returns, the local variables are no longer
available.
• Local variables are defined like any other variables.
• The parameters passed in to the function are also
considered local variables and can be used exactly as if they
had been defined within the body of the function.
• Variables declared within the function are said to have
"local scope."
19
Example
The use of local variables and parameters.
#include <iostream>
Using namespace std;
float Convert(float);
int main()
{
float TempFer;
float TempCel;
cout << "Please enter the temperature in Fahrenheit: ";
cin >> TempFer;
TempCel = Convert(TempFer);
cout << "\nHere's the temperature in Celsius: ";
cout << TempCel << endl;
return 0;
}
float Convert(float TFer)
{
float TCel;
TCel = ((TFer - 32) * 5) / 9;
return TCel;
}
20
Global Variables
• Variables defined outside of any function have global scope
and thus are available from any function in the program,
including main().
• The term global means that the variable has scope
throughout the program. Since the variable has scope
throughout the program, its lifetime does not end until the
program ends.
• To make a variable global, it must be declared above all
function definitions, generally with function prototypes
21
Example-Demonstrating global and local variables
#include <iostream>
void myFunction(); // prototype
int x = 5, y = 7; // global variables
int main()
{
cout << "x from main: " << x << "\n";
cout << "y from main: " << y << "\n\n";
myFunction();
cout << "Back from myFunction!\n\n";
cout << "x from main: " << x << "\n";
cout << "y from main: " << y << "\n";
return 0;
}
void myFunction()
{
int y = 10;
cout << "x from myFunction: " << x << "\n";
22
cout << "y from myFunction: " << y << "\n\n";
Sending Information to a Function
• The printMessage function in the Hello World program
outputs “Hello world!” It does not need any further
information to do its job.
• Let’s make the printMessage function more useful so that it
does not always output “Hello world” but instead outputs
whatever message we ask it to.
• Arguments are information that is provided to a function
so that it may perform its task.
• The two ways of passing arguments, by value and by
reference
23
Passing Arguments by Value
• The arguments passed in to the function are local to the
function.
• Changes made to the arguments do not affect the values in
the calling function. This is known as passing by value,
which means a local copy of each argument is made in the
function.
• These local copies are treated just like any other local
variables.
24
Example
Demonstration of passing by value
#include <iostream>
#include <string>
using namespace std;
void printMessage(string);
int main ()
{
string str=“John”;
printMessage(str);
return 0;
}
void printMessage(string s)
{
cout << "Your Name is " << s;
} 25
Pass by reference
• Passing arguments by value is fine when you don’t want to
change their value in the called function.
• In C++, passing by reference is accomplished in two ways:
– using pointers and using references.
• The syntax is different, but the net effect is the same.
• Rather than a copy being created within the scope of the
function, the actual original object is passed into the
function.
• Passing an object by reference allows the function to
change the object being referred to.
26
Inline Functions
• Inline function in C++ is an enhancement feature that
improves the execution time and speed of the program.
Syntax
inline return_type function_name ( type
parameterName1, type parameterName2...)
{
statements;
}
27
Example
28
Recursive Function
• Recursive Function is simply a function that calls itself
somewhere in the function body and that terminates when
a base case is met.
• A recursive definition has two parts:
– the base case-a stopping condition
– the recursive step-an expression of the computation or
definition in terms of itself.
• It's easier to solve certain problems with recursion as the
resulting code is usually shorter
• Sometimes its the only way.
29
Example
#include<iostream>
using namespace std;
long fact(int x);
int main(){
int a,f;
cout<<“enter a number \n";
cin>>a;
f=fact(a);
cout<<“The factorial of a number is”<<f<<endl;
return 0;
}
-------------------The End-------------------
31