CS2431 Lecture 4 2023
CS2431 Lecture 4 2023
PROGRAMMING FUNDAMENTALS
Lecture 4 – Functions
Ndaba B
ISAS 113
Department of Mathematics & Computer Science
National University of Lesotho
2023/2024 @NUL 1
Outline
❑ Introduction
❑ Writing Functions
― Declaration
― Definition
― Header and source files
❑ Calling Functions
― Function call operator
― Argument passing
❑ Kinds of Functions
― Inline functions
― Overloaded functions
― Function templates
― Recursive functions
― Built-in functions
2023/2024 @NUL 2
Introduction
2023/2024 @NUL 3
What is a function?
❑ A named group of statements that perform a particular task
❑ Functions are used to package code
❑ A program that prints all double base palindromes between a
given range might include the functions
― isDecPalindrome: check if a given decimal is palindromic
― isBinPalindrome: check if a given binary is palindromic
― displayDoublePalindromes: display double palindromes
2023/2024 @NUL 4
What is a function?
The explosive growth of Internet communications and data storage on
Internet-connected computers has greatly increased privacy concerns. The field of
cryptography is concerned with coding data to make it difficult (and hopefully—with
the most advanced schemes—impossible) for unauthorized users to read. In this
exercise you’ll investigate a simple scheme for encrypting and decrypting data.
A company that wants to send data over the Internet has asked you to write a
program that will encrypt it so that it may be transmitted more securely. All the data
is transmitted as four-digit integers. Your application should read a four-digit integer
entered by the user and encrypt it as follows: Replace each digit with the result of
adding 7 to the digit and getting the remainder after dividing the new value by 10.
Then swap the first digit with the third, and swap the second digit with the fourth.
Then print the encrypted integer. Write a separate application that inputs an
encrypted four-digit integer and decrypts it (by reversing the encryption scheme) to
form the original number – {Question quoted from C++ How to Program (2012) p.g
151}.
2023/2024 @NUL 5
Why Functions?
❑ Modularity
― Divide-and-conquer
― Promotes re-usability
― Makes program easy to debug
― Makes program easy to maintain
❑ Re-usability
― Function body written only once and re-used
❑ Maintainability
― Program easy to maintain
2023/2024 @NUL 6
Example Functions
#include<iostream>
❑ Built-in functions #include<cmath>
― Many pre-defined functions in double addTwoNumbers(double x, double y){
the C++ Standard Library double tempSum=a+b;
❑ Standard Library functions return tempSum;
}
― Common mathematical int main(){
operations double a=0.0, b=0.0, sum=0.0, sumsqrt=0.0;
― String manipulations std::cout<<“a? ”;
std::cin>>a;
― Input/output
std::cout<<“b? ”;
― Error checking etc std::cin>>b;
❑ User-defined functions sum=addTwoNumbers(a,b);
std::cout<<“The sum of ”<<a<<“ and ”<<b<<“is ”;
― Functions written by the
std::cout<<sum<<“\n”;
programmer
sumsqrt=sqrt(sum);
― aka Programmer-defined std::cout<<“The sqrt of ”<<sum<<“ is ”<<sumsqrt;
return 0;
}
2023/2024 @NUL 7
Writing Functions
2023/2024 @NUL 8
Function Declaration
❑ Introduces the function name and its type
❑ Also known as a function prototype
#include<iostream>
return_type function_name (parameter_list); double addTwoNumbers(double x, double y);
int main(){
double a=0, b=0, sum=0;
❑ return_type std::cout<<“Welcome to Addition Program \n”;
― Type of final output data generated std::cout<<“a? ”;
by the function
std::cin>>a;
― Cannot be a function type or an
array std::cout<<“b? ”;
❑ function_name std::cin>>b;
― Must be meaningful .
❑ parameter_list .
.
― Comma-separated list of function
parameters return 0;
― Determines arguments to be }
specified when function is called
2023/2024 @NUL 9
Function Definition
❑ Associates the function body with the #include<iostream>
function name and parameter list double addTwoNumbers(double x, double y);
int main(){
double a=0, b=0, sum=0;
return_type functionName (parameter_list) std::cout<<“Welcome to Addition Program \n”;
function_body; std::cout<<“a? ”;
std::cin>>a;
std::cout<<“b? ”;
❑ function_body std::cin>>b;
― Specifies the complete …
behaviour of the function return 0;
― A compound statement }
double addTwoNumbers(double x, double y){
double tempSum=0;
tempSum=x+y;
return tempSum;
}
2023/2024 @NUL 10
Separation of Concerns
❑ Separate function declarations from function definitions
― Program easy to maintain
― Hide implementation
❑ Put declarations in header files
― File extension (.h)
❑ Put definitions in source files
― File extension (.cpp)
― Include the header that declares a function in the source file that defines that
function
❑ Use conditional inclusion preprocessor directives to avoid multiple
definitions
2023/2024 @NUL 11
Separation of Concerns
#include<iostream> #include<iostream>
#include “functions.h” #ifndef FUNCTIONS_H
Header file: functions.h
#define FUNCTIONS_H
int main(){ Main program: main.cpp double addTwoNumbers(double x, double y);
double a=0, b=0, sum=0; //declaration for function addTwoNumbers
std::cout<<“Welcome to Addition Program \n”; #endif
std::cout<<“a? ”;
std::cin>>a; #include “functions.h”
std::cout<<“b? ”; #ifndef FUNCTIONS_CPP Source file: functions.cpp
std::cin>>b; #define FUNCTIONS_CPP
sum=addTwoNumbers(a,b); double addTwoNumbers(double x, double y){
std::cout<<“The sum is ”<<sum; //definition for function addTwoNumbers
return 0; double tempSum=0;
} tempSum=x+y;
return tempSum;
}
#endif
2023/2024 @NUL 12
Function Calling
2023/2024 @NUL 13
Function Call Operator
#include<iostream>
double addTwoNumbers(double x, double y);
int main(){
function_name (argument_list);
double a=0, b=0, sum=0;
std::cout<<“Welcome to Addition Program \n”;
std::cout<<“a? ”;
❑ To use a function std::cin>>a;
❑ Use the function call operator std::cout<<“b? ”;
f(…) std::cin>>b;
❑ Specify the function name and sum=addTwoNumbers(a,b);
give appropriate arguments std::cout<<“The sum is ”;
2023/2024 @NUL 14
Arguments Passing
❑ Arguments are initialisers for function’s parameters
❑ Arguments and parameters must match
― Type
― Number
❑ Two main ways of passing arguments
― By value
― By reference
2023/2024 @NUL 15
Arguments Passing by Value
❑ Function parameter is initialised with int a=10;
a copy of the argument int b=a;
❑ Parameter and argument are b=42;
independent objects
❑ We say arguments are “passed by
value” or the function is “called by
value” #include<iostream>
#include “functions.h”
#include “functions.h”
#ifndef FUNCTIONS_CPP int main(){
#define FUNCTIONS_CPP double a=0, b=0, sum=0;
double addTwoNumbers(double x, double y){ std::cout<<“Welcome to Addition Program \n”;
//definition for function addTwoNumbers std::cout<<“a? ”;std::cin>>a;
double tempSum=0; std::cout<<“b? ”;std::cin>>b;
tempSum=x+y; sum=addTwoNumbers(a,b);
return tempSum; std::cout<<“The sum is ”<<sum;
} return 0;
#endif }
2023/2024 @NUL 16
Arguments Passing by Reference
❑ Reference parameter bound directly int a=10;
to the object from which it is int &b=a;
b=42;
initialised. i.e no copying
❑ We say arguments are “passed by
reference” or the function is “called
by reference” #include<iostream>
#include “functions.h”
#include “functions.h”
#ifndef FUNCTIONS_CPP int main(){
#define FUNCTIONS_CPP double a=0, b=0, sum=0;
double addTwoNumbers(double & x, double & y){ std::cout<<“Welcome to Addition Program \n”;
//definition for function addTwoNumbers std::cout<<“a? ”;std::cin>>a;
double tempSum=0; std::cout<<“b? ”;std::cin>>b;
tempSum=x+y; sum=addTwoNumbers(a,b);
return tempSum; std::cout<<“The sum is ”<<sum;
} return 0;
#endif }
2023/2024 @NUL 17
Function Swap Example
#include<iostream>
#ifndef FUNCTIONS_H
#define FUNCTIONS_H
What is the output of this program? void swap(double & x, double & y);
//declaration for function swap
#endif
2023/2024 @NUL 18
Function Swap Example: const objects
#include<iostream>
#ifndef FUNCTIONS_H
#define FUNCTIONS_H
What is the output of this program? void swap(const double & x, const double & y);
//declaration for function swap
#endif
2023/2024 @NUL 19
Function Call Stack
❑ Stack
― Last-in, first-out (LIFO) data structure
― Insert (push), remove (pop)
❑ Function call stack
― Used “behind the scenes” to manage function calls
― During function calls, control is passed from one function to
another
― Each calling function need to know from whence to resume
when the called function exits
❑ How it works
― When a function is called: a record (stack frame) containing
the return address (and a function’s local automatic variables)
is created and pushed into the stack
― When a function ends execution: a frame is popped from the
stack, and control continues from the return address specified
in the popped frame
❑ Use of the call stack results in overhead
― may lead to stack overflow if allocated stack memory used up
2023/2024 @NUL 20
Function Call Stack Example
Trace fully, the contents of the function call stack for the #include<iostream>
following program. #ifndef FUNCTIONS_H
#define FUNCTIONS_H
#include “functions.h” void solveQuadratic (double, double, double);
#ifndef FUNCTIONS_CPP double discriminant(double ,double,double);
#define FUNCTIONS_CPP double square(double );
void solveQuadratic (double a , double b , double c ){ #endif
double d = discriminant(a ,b ,c );
....
} #include<iostream>
double discriminant(double a ,double b ,double c ){ #include “functions.h”
double d = square (b) - 4ac;
return d; int main(){
} double a=1.0, b=1.0, c=1.0;
double square(double x ){ solveQuadratic(a,b,c);
return x*x;
} return 0;
#endif }
2023/2024 @NUL 21
Special Functions
2023/2024 @NUL 22
Inline Functions
❑ Used to avoid function call overhead
― Copying the arguments
― Retrieving the result
❑ Request the compiler to expand the function “in-line” instead
of performing the normal function call
❑ Inline specification is only a request to the compiler. The
compiler may choose to ignore the request.
❑ Disadvantage
― May result in a larger executable file
2023/2024 @NUL 23
Inline Function Example
#include<iostream> #include<iostream>
#include “functions.h” #ifndef FUNCTIONS_H
#define FUNCTIONS_H
int main(){ inline double addTwoNumbers(double x, double y);
double a=0, b=0, sum=0; //declaration for function addTwoNumbers
std::cout<<“Welcome to Addition Program \n”; #endif
std::cout<<“a? ”;
std::cin>>a; #include “functions.h”
std::cout<<“b? ”; #ifndef FUNCTIONS_CPP
std::cin>>b; #define FUNCTIONS_CPP
sum=addTwoNumbers(a,b); inline double addTwoNumbers(double x, double y){
std::cout<<“The sum is ”<<sum; //definition for function addTwoNumbers
return 0; double tempSum=0;
} tempSum=x+y;
return tempSum;
}
#endif
2023/2024 @NUL 24
Overloaded Functions
❑ Functions that have the same name but different
implementations
― Different parameter list
― Enable functional polymorphism
❑ Advantages
― Simplicity
❑ The main() function may not be overloaded
2023/2024 @NUL 25
Overloaded Functions Example
#include<iostream> #include<iostream>
#include “functions.h” #ifndef FUNCTIONS_H
#define FUNCTIONS_H
double add(double x, double y);
int main(){ int add(int x, int y);
double a=9.0, b=8.0, c=7.0, sum=0.0; double add(double x, double y, double z);
sum=add(a,b);//??? #endif
sum=add(a,b,c);//???
sum=add(7,8,9);//???
#include “functions.h”
sum=add(2,1);//???
#ifndef FUNCTIONS_CPP
#define FUNCTIONS_CPP
return 0; double add(double x, double y){
} return x+y;
}
int add(int x, int y){
return x+y;
}
double add(double x, double y , double z){
return x+y+z;
}
#endif
2023/2024 @NUL 26
Function Templates
❑ Overloaded functions are used to perform similar operations
that involve different program logic on different data types
❑ If the program logic and operations are identical for each data
type, overloading may be performed more compactly and
conveniently by using function templates
❑ A function template define a family of functions
❑ How to use function templates
― Write a single function template definition
― For each function template instantiation, compiler automatically
generates separate function template specialisations to handle each
call appropriately
2023/2024 @NUL 27
Function Templates Example
#include<iostream> #ifndef FUNCTIONS_CPP
#include “functions.cpp” #define FUNCTIONS_CPP
int main(){
template<typename T>
double a=9.0, b=8.0, c=7.0, sum=0.0;
sum=add<double>(a,b); T add(T x, T y);
sum=add(a,b);
sum=add(a,b,c); template<typename T>
sum=add(7,8); T add(T x, T y){
return x+y;
return 0;
}
}
#endif
2023/2024 @NUL 28
Some Built-in Functions
2023/2024 @NUL 29
Built-in Functions: random number
generator
❑ Function int rand(void)
― Randomly generates an unsigned integer in the range (0, RAND_MAX]
― RAND_MAX is a symbolic constant defined in <cstdlib> header
― Range of values produced often different from specific application
requirements, hence the rand expression must be scaled using a
modulus operator with an appropriate scaling factor
❑ Function srand(unsigned)
― Function rand() actually generates pseudo-random numbers
― Function srand(seed) is used to randomise (seed) rand so that it
produces different sequence of numbers for each execution
― Creates nondeterministic random numbers
2023/2024 @NUL 30
Built-in Functions: random number
generator
#include<iostream>
#include<cstdlib>//include to use rand
int main(){
for (int i=0;i<10;i++)
std::cout<<“random number ”<<i<<“=”<<rand()<<“\n”;
return 0;
}
2023/2024 @NUL 31
Built-in Functions: random number
generator
2023/2024 @NUL 32
Recursion
2023/2024 @NUL 33
Recursion
❑ A function which calls itself is said to be “recursive”
— Solve a bigger problem by breaking it into pieces and calling the subprogram itself to
solve the pieces
❑ Recursion is applicable only to problems which can be expressed in terms of
themselves
— Not all problems can be solved recursively
— The first step in developing a recursive solution to a task is to first express the solution in
terms of itself
❑ Recursive definition must have at least one valid terminal (boundary) condition
— Causes recursive function to fold back
— Otherwise, stack overflow will result
❑ Every recursive function can be written using iteration constructs
❑ Why recursion?
— Code elegance
❑ Disadvantages of recursion?
— Performance
2023/2024 @NUL 34
Recursion Example: Factorial
Base case
Recursive case
2023/2024 @NUL 35
Recursion Example: Factorial
2023/2024 @NUL 36
Conclusion
❑ Writing Functions
― Declaration
― Definition
― Header and source files
❑ Calling Functions
― Function call operator
― Argument passing
❑ Kinds of Functions
― Inline functions
― Overloaded functions
― Function templates
― Recursive functions
― Built-in functions (random number generation)
2023/2024 @NUL 37