0% found this document useful (0 votes)
14 views94 pages

4 All

The document discusses functions in C++ including declaring functions, calling functions, and passing parameters to functions. It provides examples of declaring functions that return values and using functions within a main program by calling the functions and storing the return values. Functions allow breaking problems into smaller reusable parts and are an important concept in programming.

Uploaded by

LAURENT JIBUNGE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views94 pages

4 All

The document discusses functions in C++ including declaring functions, calling functions, and passing parameters to functions. It provides examples of declaring functions that return values and using functions within a main program by calling the functions and storing the return values. Functions allow breaking problems into smaller reusable parts and are an important concept in programming.

Uploaded by

LAURENT JIBUNGE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 94

FUNCTIONS

OVERVIEW
OVERVIEW
 In real life, we often find ourselves doing the same task
over and over
 Example: make toast and jam for breakfast in the morning
 Example: drive our car from home to work and back

 Once we have decided on our favorite way to do these


tasks, we can write down the steps we normally take
 Make a recipe card for making breakfast items
 Write down series of turns to travel from A to B
 This written descriptions will let others reuse our work

CP 123: Introduction to Higher Level Programming


OVERVIEW
 Functions in C++ can be used much in the same way
 We write down the code we want to reuse when we
declare the function
 Then to execute this code, we call the function from the
main program

 This approach is a big time saver for programmers


because they can focus on implementing and debugging
smaller pieces of code, and then reuse this work

CP 123: Introduction to Higher Level Programming


OVERVIEW
 Functions play an important role in software development
 Break a big problem down into a sequence of smaller
problems that we know how to solve
 Implement and test solutions to each of the smaller
problems using functions
 Use the functions we created above to create an effective
solution to the big problem

 Functions in the same “category” are often packaged


together to create function libraries
 C++ has function built in libraries for input/output, string
manipulation, mathematics, random numbers, etc.

CP 123: Introduction to Higher Level Programming


OVERVIEW

 Lesson objectives:
 Learn the syntax for declaring functions in C++
 Learn how to call and trace the execution of functions
 Learn how to pass value and reference parameters
 Study example programs showing their use
 Complete online labs on functions
 Complete programming project using functions

CP 123: Introduction to Higher Level Programming


FUNCTIONS

PART 1
DECLARING FUNCTIONS
DECLARING FUNCTIONS
 In order to declare a function in C++ we need to provide
the following information:
 The name of the function
 List of operations to be performed
 Type of data value to be returned
 Types and names of parameters (if any)
 Declaration of local variables (if any)
 Value to be returned to the main program (if any)

CP 123: Introduction to Higher Level Programming


DECLARING FUNCTIONS
 Function return values
 The return( ) statement exits function with specified value
 You can use return( ) anywhere in function, but the bottom
of the function is preferred

 The type of the return value depends on the application


 Typical mathematical functions return float values
 Typical I/O functions return input data or error/success flag
 Some functions perform calculations but return no value
(we use the special data type “void” in this case)

CP 123: Introduction to Higher Level Programming


DECLARING FUNCTIONS
 Consider the following task:
 Declare an integer variable
 Prompt the user to input a value between 1..9
 Read the integer value from the user
 Check the range of the input value
 Perform calculation on input value

 We can declare a C++ function to package this code


together so it can be reused in different programs

CP 123: Introduction to Higher Level Programming


DECLARING FUNCTIONS
// Function declaration example Name of the
int Lucky() function we are
declaring
{
int Number;
cout << "Pick a number between 1..9: ";
cin >> Number;
if ((Number >= 1) && (Number <= 9))
Number = 42 / Number;
return( Number );
}

CP 123: Introduction to Higher Level Programming


DECLARING FUNCTIONS
// Function declaration example
int Lucky()
{
int Number;
cout << "Pick a number between 1..9: ";
Operations to
cin >> Number;
be performed
if ((Number >= 1) && (Number <= 9)) by the function

Number = 42 / Number;
return( Number );
}

CP 123: Introduction to Higher Level Programming


DECLARING FUNCTIONS
// Function declaration example
int Lucky() Data type of
the function
{ return value
int Number;
cout << "Pick a number between 1..9: ";
cin >> Number;
if ((Number >= 1) && (Number <= 9))
Number = 42 / Number;
return( Number );
}

CP 123: Introduction to Higher Level Programming


DECLARING FUNCTIONS
// Function declaration example
int Lucky()
Local variable
{ which can only be
int Number; accessed and
used from within
cout << "Pick a number between 1..9: "; this function
cin >> Number;
if ((Number >= 1) && (Number <= 9))
Number = 42 / Number;
return( Number );
}

CP 123: Introduction to Higher Level Programming


DECLARING FUNCTIONS
// Function declaration example
int Lucky()
{
int Number;
cout << "Pick a number between 1..9: ";
cin >> Number;
if ((Number >= 1) && (Number <= 9))
Number = 42 / Number; Value returned by
the function to the
return( Number ); main program
}

CP 123: Introduction to Higher Level Programming


CALLING FUNCTIONS
 Now that we have declared the function called Lucky how
can we use this function in the main program?
 We need to specify the following in a function call
 The name of the function we wish to execute
 Variables passed in as parameters (if any)
 Operations to be performed with return value (if any)

 The main program will jump to function code, execute it,


and return with the value that was calculated
 Return values can be used to assign variables or they can
be output (we should not ignore them)

CP 123: Introduction to Higher Level Programming


CALLING FUNCTIONS
int main()
{ This function call will
cause the main program
… to jump to the Lucky
/Function usage example function, execute that
code and store the return
int Num; value in variable Num
Num = Lucky();
cout << "Your Lucky number is " << Num << endl;

}

CP 123: Introduction to Higher Level Programming


CALLING FUNCTIONS
 We can trace the executions functions in a program using
the “black box” method
 Draw a box for the main program
 Draw a second box for the function being called
 Draw an arrow from the function call in the main program
to the top of the function being called
 Draw a second arrow from the bottom of the function back
to the main program labeled with the return value
 Using this black box diagram we can visualize the
execution of the program by following the arrows

CP 123: Introduction to Higher Level Programming


CALLING FUNCTIONS

int main() int Lucky()


{ {

return(…)
Num = Lucky() }

We leave the main


program and jump to
} the Lucky function

CP 123: Introduction to Higher Level Programming


CALLING FUNCTIONS

int main() int Lucky()


{ {

return(…)
Num = Lucky() }

We then execute the code


inside the Lucky function
}

CP 123: Introduction to Higher Level Programming


CALLING FUNCTIONS

int main() int Lucky()


{ {

return(…)
Num = Lucky() 6 }

When we reach the bottom of


… the Lucky function we return a
} value to the main program
In this case, if the user enters
7 the return value would be 6

CP 123: Introduction to Higher Level Programming


CALLING FUNCTIONS
int main()
{ You can call the function
… more than once. Each
time you call it, the
/Function usage example
function will be executed
int Num;
Num = Lucky();
cout << “Your Lucky number is << Num << endl;

Num = Lucky();
cout << "Your Lucky number is " << Num << endl;

}

CP 123: Introduction to Higher Level Programming


CALLING FUNCTIONS
int main()
{… You can call the function
with different variables
//Function usage example
int Num, Value;
Num = Lucky();
Value = Lucky();
cout << "Your Lucky number is " << Num << endl;
cout << “Your second Lucky number is << Value << endl;

}

CP 123: Introduction to Higher Level Programming


CALLING FUNCTIONS
// Function with multiple returns
float Magic()
{
int Height, Weight;
cout << "Enter your height in inches: ";
cin >> Height;
cout << "Enter your weight in pounds: ";
cin >> Weight; This function has two
if ((Height > 0) && (Weight > 0)) return statements,
one for valid user
return(Height/Weight);
input data and one
else for invalid input data
return(-1);
}

CP 123: Introduction to Higher Level Programming


CALLING FUNCTIONS
// Style: prefer to have only one return
float Magic()
{
int Height, Weight;
float Result;
cout << "Enter your height in inches: ";
cin >> Height;
cout << "Enter your weight in pounds: ";
cin >> Weight; This function sets a
if ((Height > 0) && (Weight > 0)) local variable to an
Result = Height/Weight); appropriate value
else that is returned as
Result = -1; the last statement.
return(Result);
}

CP 123: Introduction to Higher Level Programming


CALLING FUNCTIONS

// Function usage example This function call will
float Value; cause the main program
to jump to the Magic
Value = Magic(); function, execute that
if (Value < 0) code and store the return
value in variable Value
cout << "You are silly" << endl;
else if (Value < 2)
cout << "You are under weight" << endl;
else if (Value > 3)
cout << "You are under tall" << endl;

CP 123: Introduction to Higher Level Programming
LOCAL AND GLOBAL VARIABLES
 “Local variables” are defined inside the main program or
any function
 Local variables are typically used to perform calculations
 Local variables can only be accessed within the function
 Initialize local variables each time the function is called

 “Global variables” are defined outside the main program


or any function
 Global variables are often used for status flags
 We can access global variables anywhere in the program
 Initialize global variables each time the program is run

CP 123: Introduction to Higher Level Programming


LOCAL AND GLOBAL
VARIABLES
// Global variables
int Value = 42; These global variables
can be used anywhere
float Pi = 3.14159; in the program

// Function declaration
float Silly()
{
// Local variables
These local variables
float Value; can only be used in the
int Data; function Silly

}

CP 123: Introduction to Higher Level Programming


LOCAL AND GLOBAL
VARIABLES
// Global variables
int Value = 42;
In this case, the local
float Pi = 3.14159; variable Value “hides”
the global variable with
the same name, so we
// Function declaration
can not access the
float Silly() global variable from
{ within this function
// Local variables
float Value;
int Data;

}

CP 123: Introduction to Higher Level Programming


LOCAL VARIABLES

// Function declaration
void FunctionOne ()
{ Multiple functions can
float Temp= 1.7; have the same local
cout << Temp << endl ; // This will output 1.7 variable; This includes
} main() and other
function(s) used by the
same program
// Function declaration
float FunctionTwo()
{
// Local variables
float Temp = 0.0;
cout << Temp << endl ; // This will output 0.0

}

CP 123: Introduction to Higher Level Programming


LOCAL AND GLOBAL VARIABLES

// Code inside Silly function
cout << "Enter your age in months: ";
cin >> Data; // Changes local variable Data
Pi = 22.0 / 7.0; // Changes global variable Pi
Value = Data * Pi; // Changes local variable Value
return(Value); // Returns local variable Value
}

CP 123: Introduction to Higher Level Programming


SUMMARY
 In this section we have shown how a function can be
declared in in C++
 We have also shown how a function can be called from
within the main program
 Finally, we discussed the difference between local and
global variables in a C++ program

CP 123: Introduction to Higher Level Programming


FUNCTIONS

PART 2
FUNCTION PARAMETERS
VALUE PARAMETERS
 A function may need some input to perform desired task
 We can pass data values into function using parameters
 We need to specify the data type and and the names of
parameters when defining a function
 We need to specify the value of the parameter when
calling the function

 Example
 To calculate the square of a number in a function, we need
to pass in the number to square as a value parameter

CP 123: Introduction to Higher Level Programming


VALUE PARAMETERS
// Function with value parameter
Number is a value
float Square( const float Number ) parameter of the
Square function
{
float Result = Number * Number;
return( Result );
}
We can use Number in
our function calculations

CP 123: Introduction to Higher Level Programming


VALUE PARAMETERS
int main()

// Calling functions with value parameters
float Num = 5;
cout << Square(3) << endl;
cout << Square(Num) << endl;

}

CP 123: Introduction to Higher Level Programming


VALUE PARAMETERS

int main() float Square(3)


{ {

cout << Square(3) return(…)


cout << Square(Num) 9 }

When we call Square(3) we


… initialize the parameter
} Number with 3 and return
the value of 3*3

CP 123: Introduction to Higher Level Programming


VALUE PARAMETERS

int main() float Square(5)


{ {

cout << Square(3) return(…)


cout << Square(Num) 25 }

When we call Square(Num)


… we initialize the parameter
} Number with 5 and return
the value of 5*5

CP 123: Introduction to Higher Level Programming


VALUE PARAMETERS
 Some comments on value parameters:
 In general, parameter passing is a much safer way to send
information into a function than using global variables
 By using “const” before the parameter data type, we can
treat value parameters like a constant within the function
 If we omit “const” we can treat the value parameter like a
local variable and modify it as needed in the function
 Changes to a value parameter in a function will NOT
change the variable in main used to call the function

CP 123: Introduction to Higher Level Programming


SUM DIGITS EXAMPLE
 Assume we are given an integer between 0..99999

 How can we calculate the sum of the digits in the number?


 Find each of the 5 digits in the number
 Add them up to get the sum of digits

 How can we implement this?


 We can write a program to do this where the main program
prompts the user for input and does error checking
 Then we can call a function to do the actual calculations
on the input value

CP 123: Introduction to Higher Level Programming


SUM DIGITS EXAMPLE
// Function to calculate sum of digits
int SumDigits(const int Number)
{
// Get digits and calculate their sum
int Digit1, Digit2, Digit3, Digit4, Digit5;
Digit1 = (Number / 10000);
Digit2 = (Number % 10000) / 1000;
Digit3 = (Number % 1000) / 100;
Digit4 = (Number % 100) / 10;
Digit5 = (Number % 10);
return (Digit1 + Digit2 + Digit3 + Digit4 + Digit5);
}

CP 123: Introduction to Higher Level Programming


SUM DIGITS EXAMPLE
// Main body of program
int main()
{
int Input;
cout << "Enter number in [0..99999] range: ";
cin >> Input;
if ((Input < 0) || (Input > 99999))
cout << "Number must be in [0..99999]" << endl;
else
cout << ”Sum digits = " << SumDigits(Input)<< endl;
return 0 ;
}

CP 123: Introduction to Higher Level Programming


SUM DIGITS EXAMPLE
Sample program output:

Enter number in [0..99999] range: 123


Magic number = 6

Enter number in [0..99999] range: 23456


Magic number = 20

Enter number in [0..99999] range: 222222


Number must be in [0..99999]

CP 123: Introduction to Higher Level Programming


REFERENCE PARAMETERS
 In some applications a function may need to change the
value of one or more variables in the main program
 We can use a reference parameters to accomplish this
 We need to specify the data type and the name of
reference parameters when defining the function
 We need to add "&" between the data type and name to
specify this is a reference parameter
 When we call the function, we give the names of variables
we want the function to have access to
 This makes the reference parameter an “alias” for the
variable in the main program

CP 123: Introduction to Higher Level Programming


REFERENCE PARAMETERS
// Function with reference parameter
void GetGrade(const float Average, char & Grade)
{
if (Average >= 90) Grade = 'A';
Grade is a reference
else if (Average >= 80) Grade = 'B'; parameter of the
else if (Average >= 70) Grade = 'C'; GetGrade function

else if (Average >= 60) Grade = 'D';


else Grade = 'F';
}

CP 123: Introduction to Higher Level Programming


REFERENCE PARAMETERS
// Function with reference parameter
void GetGrade(const float Average, char & Grade)
{
if (Average >= 90) Grade = 'A';
else if (Average >= 80) Grade = 'B'; Changes to Grade in
this function will modify
else if (Average >= 70) Grade = 'C';
some variable in the
else if (Average >= 60) Grade = 'D'; main program
else Grade = 'F';
}

CP 123: Introduction to Higher Level Programming


REFERENCE PARAMETERS
// Function with reference parameter
void GetGrade(const float Average, char & Grade)
{
if (Average >= 90) Grade = 'A';
else if (Average >= 80) Grade = 'B';
else if (Average >= 70) Grade = 'C';
else if (Average >= 60) Grade = 'D';
else Grade = 'F';
} Notice that this is a
void function and there
is no return statement

CP 123: Introduction to Higher Level Programming


REFERENCE PARAMETERS
int main()
{

Grade is now an alias
// Calling function with reference parameter
for NewGrade in the
float NewScore = 86.4; GetGrade function
char NewGrade = ' ';
GetGrade(NewScore, NewGrade);
cout << "Your final grade is " << NewGrade << endl;

}

CP 123: Introduction to Higher Level Programming


REFERENCE PARAMETERS
 Advantages:
 We can use reference parameters to modify multiple
variables in the main program
 No data is copied from the main program to the function
when we make the function call (unlike value parameters)

 Disadvantages
 We must provide a variable name when calling functions
with reference parameters
 Keeping track of the “aliases” created by reference
parameters is more difficult than tracing value parameters

CP 123: Introduction to Higher Level Programming


PRIME FACTORS EXAMPLE
 Assume we are given an integer between 1..100

 How can we calculate and print the prime factors?


 Check to see how many times the prime numbers 2,3,5,7
divide evenly into the input value (i.e. input % factor == 0)

 How can we implement this?


 We can write a program to do this where the main program
prompts the user for input and does error checking
 Then we can call a function to check to see how many
times each of the prime numbers above are factors

CP 123: Introduction to Higher Level Programming


PRIME FACTORS EXAMPLE
// Function to check prime factors
void CheckFactors( int & Number, const int Factor )
{
while (Number % Factor == 0) Number is a reference
{ parameter and Factor is a
value parameter
cout << Factor << " is a factor\n";
Number = Number / Factor;
}
} Here is where we modify
the reference parameter
which is an alias for a
variable in main program
CP 123: Introduction to Higher Level Programming
PRIME FACTORS EXAMPLE
// Main body of program
int main()
{
// Get user input
int Num;
cout << "Enter number in [1..100] range: ";
cin >> Num;

// Check input value


if ((Num < 1) || (Num > 100))
cout << "Number must be in [1..100]" << endl;
CP 123: Introduction to Higher Level Programming
PRIME FACTORS EXAMPLE

// Calculate prime factors
else
{
CheckFactors(Num, 2);
We call the CheckFactors
CheckFactors(Num, 3); function four times to
CheckFactors(Num, 5); check primes 2,3,5,7

CheckFactors(Num, 7);
if (Num > 1) cout << Num << " is a factor\n";
}

CP 123: Introduction to Higher Level Programming


PRIME FACTORS EXAMPLE
Sample program output:

Enter number in [1..100] range: 42


2 is a factor
3 is a factor
7 is a factor

Enter number in [1..100] range: 65


5 is a factor
13 is a factor

CP 123: Introduction to Higher Level Programming


SUMMARY
 In this section we have described how value parameters
and reference parameters can be used to get data in and
out of functions
 Value parameters: “const int Number”
 Reference parameters: “float & Value”

 We have also shown two example programs that use


functions with parameters to solve problems
 Sum of digits
 Prime factors

CP 123: Introduction to Higher Level Programming


FUNCTIONS

PART 3
RECURSION
RECURSION
 Recursion is a very powerful problem solving method

 Recursive functions call themselves to solve problems


 We reduce "size" of problem each recursive function call
 Need to have a terminating condition to stop recursion
 Visualize using black box method with inputs and returns

 Recursive solutions can also be implemented via iteration


 Sometimes the recursive function is smaller
 Sometimes the iterative function is faster

CP 123: Introduction to Higher Level Programming


RECURSION
 Example: calculating N factorial

 Recursive solution solves problem in terms of itself


 Factorial(N) = N * Factorial(N-1)
 This is the recurrence relationship

 We must stop at some point


 Factorial(1) = 1
 This is the terminating condition

CP 123: Introduction to Higher Level Programming


RECURSION
// Recursive Factorial function
int Factorial(const int Num)
{ This is the terminating
condition of for the
if (Num <= 1) recursive function
return(1);
else
return( Num * Factorial(Num-1) ); Notice that we are
recursively calling the
} Factorial function with a
smaller parameter value

CP 123: Introduction to Higher Level Programming


RECURSION

int main() int Factorial(3)


{ {
… …
Factorial(3) Factorial(2)
… …
} }

• First, the main program calls Factorial(3)

CP 123: Introduction to Higher Level Programming


RECURSION

int main() int Factorial(3) int Factorial(2)


{ { {
… … …
Factorial(3) Factorial(2) Factorial(1)
… … …
} } }

• First, the main program calls Factorial(3)


• Then, Factorial(3) calls Factorial(2)

CP 123: Introduction to Higher Level Programming


RECURSION

int main() int Factorial(3) int Factorial(2) int Factorial(1)


{ { { {
… … … …
Factorial(3) Factorial(2) Factorial(1)
… … … …
} } } }

• First, the main program calls Factorial(3)


• Then, Factorial(3) calls Factorial(2)
• Then, Factorial(2) calls Factorial(1)

CP 123: Introduction to Higher Level Programming


RECURSION

int main() int Factorial(3) int Factorial(2) int Factorial(1)


{ { { {
… … … …
Factorial(3) Factorial(2) Factorial(1)
… … … …
} } } }
1
• First, the main program calls Factorial(3)
• Then, Factorial(3) calls Factorial(2)
• Then, Factorial(2) calls Factorial(1)
• Then, Factorial(1) returns 1

CP 123: Introduction to Higher Level Programming


RECURSION

int main() int Factorial(3) int Factorial(2) int Factorial(1)


{ { { {
… … … …
Factorial(3) Factorial(2) Factorial(1)
… … … …
} } } }
2 1
• First, the main program calls Factorial(3)
• Then, Factorial(3) calls Factorial(2)
• Then, Factorial(2) calls Factorial(1)
• Then, Factorial(1) returns 1
• Then, Factorial(2) returns 2*1=2

CP 123: Introduction to Higher Level Programming


RECURSION

int main() int Factorial(3) int Factorial(2) int Factorial(1)


{ { { {
… … … …
Factorial(3) Factorial(2) Factorial(1)
… … … …
} } } }
6 2 1
• First, the main program calls Factorial(3)
• Then, Factorial(3) calls Factorial(2)
• Then, Factorial(2) calls Factorial(1)
• Then, Factorial(1) returns 1
• Then, Factorial(2) returns 2*1=2
• Finally, Factorial(3) returns 3*2=6

CP 123: Introduction to Higher Level Programming


RECURSION
 In this case the iterative solution is the same size and will
run slightly faster than the recursive solution

// Iterative Factorial function


int Factorial(const int Num)
{
int Product = 1;
for (int Count = 1; Count <= Num; Count++)
Product = Product * Count;
return( Product );
}

CP 123: Introduction to Higher Level Programming


RECURSION
 Example: calculating sum of all numbers from 1..N

 Recursive solution solves problem in terms of itself


 Sum(N) = N + Sum(N-1)
 This is called the recurrence relationship

 We must stop at some point


 Sum(1) = 1
 This is called the terminating condition

CP 123: Introduction to Higher Level Programming


RECURSION
// Recursive summation function
int Sum(const int Num)
{ This is the terminating
condition of for the
if (Num <= 1) recursive function
return(1);
else
return( Num + Sum(Num-1) ); Notice that we are
recursively calling the
} Sum function with a
smaller parameter value

CP 123: Introduction to Higher Level Programming


RECURSION

int main() int Sum(3) int Sum(2) int Sum(1)


{ { { {
… … … …
Sum(3) Sum(2) Sum(1)
… … … …
} } } }
6 3 1
• First, the main program calls Sum(3)
• Then, Sum(3) calls Sum (2)
• Then, Sum(2) calls Sum (1)
• Then, Sum(1) returns 1
• Then, Sum(2) returns 2+1=3
• Finally, Sum(3) returns 3+3=6

CP 123: Introduction to Higher Level Programming


RECURSION
 In this case the iterative solution is the same size and will
run slightly faster than the recursive solution

// Iterative summation function


int Sum(const int Num)
{
int Total = 0;
for (int Count = 0; Count <= Num; Count++)
Total = Total + Count;
return(Total);
}

CP 123: Introduction to Higher Level Programming


RECURSION
 Example: calculating the Nth Fibonacci number from the
sequence 1,1,2,3,5,8,13,21,34,55…

 Recursive solution solves problem in terms of itself


 Fibonacci(N) = Fibonacci(N-1) + Fibonacci(N-2)
 This is the recurrence relationship

 We must stop at some point


 Fibonacci(1) = 1
 Fibonacci(2) = 1
 These are the terminating conditions

CP 123: Introduction to Higher Level Programming


RECURSION
 This recursive function calls itself twice each time it is called
so there are a lot of function calls to calculate the answer

// Recursive Fibonacci function


int Fibonacci(const int Num)
{
if (Num <= 2)
return(1);
else
return( Fibonacci(Num-1) + Fibonacci(Num-2) );
}

CP 123: Introduction to Higher Level Programming


RECURSION
// Iterative Fibonacci function
int Fibonacci(const int Num)
{
int Num1 = 1;
int Num2 = 1;  This iterative function
for (int Count = 1; Count < Num; Count++) is slightly longer than
{ the recursive solution
but it is much faster
int Num3 = Num1 + Num2;
at run time
Num1 = Num2;
Num2 = Num3;
}
return (Num1);
}

CP 123: Introduction to Higher Level Programming


RECURSION
 What happens if we make a mistake implementing the
recurrence relationship?
 If the recursive function call has the same parameter value
the function will call itself forever
 This programming bug is called infinite recursion
 Your program will crash with a message like “stack
overflow” because it ran out of memory

CP 123: Introduction to Higher Level Programming


RECURSION
// Infinite recursion function
int Forever(int Num)
{
if (Num < 0)
return(0);
else We are recursively
return( Forever(Num) + 1 ); calling the Forever
function with the same
} parameter value

CP 123: Introduction to Higher Level Programming


RECURSION
 The corresponding iterative program will not crash, but it
will run forever adding one to the Total variable

// Infinite iteration function


int Forever(int Num)
{
int Total = 0;
while (Num < 0)
Total = Total + 1;
return( Total );
}

CP 123: Introduction to Higher Level Programming


RECURSION
 When two functions call each other recursively it is called
mutual recursion
 Function A calls function B, and function B calls function A

 Normally functions are defined before they are used


How can we do this for mutual recursion?
 The solution is to provide function headers
 These give the “signature” of the function (return type,
function name, and function parameters)
 Function headers are placed at the top of the program

CP 123: Introduction to Higher Level Programming


RECURSION
#include <iostream
using namespace std;

// Function headers
These function headers tell
int Silly(int Num); the compiler what these
functions will look like, so it
int Magic(int Val);
can properly handle calls to
these functions in the code

CP 123: Introduction to Higher Level Programming


RECURSION This debugging line will let us
see what recursive calls
// Function declaration occur when the program runs

int Silly(int Num)


{
cout << "calling silly " << Num << endl;
if (Num < 42)
return( Num + 13 );
else
return( Magic(Num*2) ); Here is the recursion call
}

CP 123: Introduction to Higher Level Programming


RECURSION This debugging line will let us
see what recursive calls
// Function declaration occur when the program runs

int Magic(int Val)


{
cout << "calling magic " << Val << endl;
if (Val > 0)
return( Val % 17 );
else
return( Silly(Val-8) ); Here is the recursion call
}

CP 123: Introduction to Higher Level Programming


RECURSION
// Main program
int main()
{
int Number;
cout << "Enter number: ";
cin >> Number;
cout << "Magic(" << Number << ") = " << Magic(Number) << endl;
cout << "Silly(" << Number << ") = " << Silly(Number) << endl;
return(0);
}

CP 123: Introduction to Higher Level Programming


RECURSION
Sample program output:

Enter number: 49

calling magic 49
Magic(49) = 15

calling silly 49
calling magic 98
Silly(49) = 13

CP 123: Introduction to Higher Level Programming


RECURSION
Sample program output:

Enter number: -10

calling magic -10


calling silly -18
Magic(-10) = -5

calling silly -10


Silly(-10) = 3

CP 123: Introduction to Higher Level Programming


SUMMARY
 In this section we have focused on recursive functions
 We need to implement the recurrence relationship
 We need to implement the terminating conditions

 Sometimes the recursive function is smaller and easier to


understand than the iterative solution

 Sometimes the recursive function is much slower because


of the large number of function calls necessary

CP 123: Introduction to Higher Level Programming


FUNCTIONS

PART 4
FUNCTION LIBRARIES
FUNCTION LIBRARIES
 Function libraries are collections of similar functions
grouped together in one file for ease of use
 By making and using libraries we can increase code reuse
and decrease development and debugging time

 To make use of the functions in a library we need to add


#include<library> at the top of our program
 This include file contains the function prototypes for all of
the functions in the library
 The compiler will automatically link in code for the
functions you have used with your program

CP 123: Introduction to Higher Level Programming


FUNCTION LIBRARIES
 Here are some of the most commonly used libraries
#include <iostream> // I/O stream functions
#include <iomanip> // I/O formatting functions
#include <fstream> // File I/O stream functions
#include <cmath> // C based math functions
#include <cstdio> // C based I/O functions
#include <cstdlib> // C based library functions
#include <cctype> // C based character functions
#include <cstring> // C based string functions
#include <ctime> // C based timing functions

 See cplusplus.com for full documentation

CP 123: Introduction to Higher Level Programming


CMATH FUNCTIONS
 The <cmath> library includes a wide range of
trigonometric functions and other functions you
remember fondly from math class
 double sin (double x);
 double cos (double x);
 double sqrt (double x);
 double log (double x);
 double pow (double base, double exponent);

 All of these functions have been implemented very


cleverly so they are fast and accurate

CP 123: Introduction to Higher Level Programming


CMATH FUNCTIONS
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
// Calculate and print sin and cos table
for (int Degrees = 0; Degrees <= 360; Degrees += 10)
{
double Radians = Degrees * M_PI / 180.0;
cout << Degrees << " " << cos(Radians) << " " << sin(Radians)<< endl;
}
return 0;
}

CP 123: Introduction to Higher Level Programming


IOMANIP FUNCTIONS
 The <iomanip> library includes functions to help you
create well formatted program output
 setw(int n);
 setprecision(int n);
 setfill(char c);

 These functions are used together with “cout” to control


how the next value will be printed on the screen

CP 123: Introduction to Higher Level Programming


IOMANIP FUNCTIONS
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
// Print header for table
cout << setw(8) << "Angle”
<< setw(8) << "Cos”
<< setw(8) << "Sin”;<< endl;

CP 123: Introduction to Higher Level Programming


IOMANIP FUNCTIONS
// Calculate and print sin and cos table
for (int Degrees = 0; Degrees <= 360; Degrees += 10)
{
double Radians = Degrees * M_PI / 180.0;
cout << setw(8) << Degrees;
cout << setw(8) << setprecision(3) << cos(Radians);
cout << setw(8) << setprecision(3) << sin(Radians) << endl;
}
return 0;
}

CP 123: Introduction to Higher Level Programming


SOFTWARE
ENGINEERING TIPS
 Start your program with "empty" function bodies
 Helps debug the main program and parameter passing

 Implement and test bodies of functions one at a time


 This way you are never far from a running program

 Print debugging messages inside each function


 To see which function is being called and its parameters

 Give functions and parameters meaningful names


 Make your code easier to read and understand

CP 123: Introduction to Higher Level Programming


SOFTWARE
ENGINEERING TIPS
 Common mistakes when creating functions
 Function definition does not match function prototype
 Semicolon at end of function definition is not needed
 Infinite loop of recursive function calls

 Common mistakes when calling functions:


 Incorrect number or types of parameters
 Incorrect ordering of parameters
 Function return value not used properly

CP 123: Introduction to Higher Level Programming


SUMMARY
 In this section we have introduced C++ function libraries
and some example programs that use these libraries
 Learning how to use the built in libraries is an important
skill for all programmers to develop
 You do not want to waste your time to reinvent a function
that has already been written and debugged

 We have also discussed several software engineering tips


for creating and debugging programs using functions

CP 123: Introduction to Higher Level Programming

You might also like