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

C++-Lesson 4 Functions-PARTB

Uploaded by

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

C++-Lesson 4 Functions-PARTB

Uploaded by

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

Learning Outcomes of the Week: WEEK 6

Computer Programming II C++

FUNCTIONS
a) Refer to pdf: Chap_04
b) C++ How to program

4/16/2024 © 2022. Cavendish University. Rights Reserved 0


3 Introduction

• Divide and conquer


– Construct a program from smaller pieces or components
– Each piece more manageable than the original program
3.2 Program Components in C++

• Programs written by
– combining new functions with “prepackaged” functions in
the C++ standard library.
– new classes with “prepackaged” classes.
• The standard library provides a rich collection of
functions.
• Functions are invoked by a function call
– A function call specifies the function name and provides
information (as arguments) that the called function needs
– Boss to worker analogy:
A boss (the calling function or caller) asks a worker (the called
function) to perform a task and return (i.e., report back) the
results when the task is done.
3.2 Program Components in C++

• Function definitions
– Only written once
– These statements are hidden from other functions.
– Boss to worker analogy:
The boss does not know how the worker gets the job done; he just
wants it done
3.3 Math Library Functions
• Math library functions
– Allow the programmer to perform common mathematical
calculations
– Are used by including the header file <cmath>
• Functions called by writing
functionName (argument)
• Example
cout << sqrt( 900.0 );
– Calls the sqrt (square root) function. The preceding
statement would print 30
– The sqrt function takes an argument of type double and
returns a result of type double, as do all functions in the
math library
3.3 Math Library Functions

• Function arguments can be


– Constants
sqrt( 4 );
– Variables
sqrt( x );
– Expressions
sqrt( sqrt( x ) ) ;
sqrt( 3 - 6x );
3.4 Functions

• Functions
– Allow the programmer to modularize a program
• Local variables
– Known only in the function in which they are defined
– All variables declared in function definitions are local variables
• Parameters
– Local variables passed when the function is called that provide
the function with outside information
Functions

• Why write functions?


– modularity
– re-use
– maintenance / testing
3.5 Function Definitions
• Create customized functions to
– Take in data
– Perform operations
– Return the result
• Format for function definition:
return-value-type function-name( parameter-list )
{
declarations and statements
}
• Example:
int square( int y)
{
return y * y;
}
3.6 Function Prototypes
• Function prototype
– Function name
– Parameters
• Information the function takes in
• C++ is “strongly typed” – error to pass a parameter of the wrong type
– Return type
• Type of information the function passes back to caller (default int)
• void signifies the function returns nothing
– Only needed if function definition comes after the function
call in the program
• Example:
int maximum( int, int, int );
– Takes in 3 ints
– Returns an int
3.7 Header Files
• Header files
– Contain function prototypes for library functions
– <cstdlib> , <cmath>, etc.
– Load with #include <filename>
• Example:
#include <cmath>

• Custom header files


– Defined by the programmer
– Save as filename.h
– Loaded into program using
#include "filename.h"
3.8 Random Number Generation
• rand function
i = rand();
– Load <cstdlib>
– Generates a pseudorandom number between 0 and RAND_MAX
(usually 32767)
• A pseudorandom number is a preset sequence of "random" numbers
• The same sequence is generated upon every program execution
• srand function
– Jumps to a seeded location in a "random" sequence
srand( seed );
srand( time( 0 ) ); //must include <ctime>
– time( 0 )
• The time at which the program was compiled
– Changes the seed every time the program is compiled, thereby
allowing rand to generate random numbers
3.8 Random Number Generation

• Scaling
– Reduces random number to a certain range
– Modulus ( % ) operator
• Reduces number between 0 and RAND_MAX to a number between
0 and the scaling factor
– Example
i = rand() % 6 + 1;
• Generates a number between 1 and 6
3.9 Example: A Game of Chance and
Introducing enum
• Enumeration - set of integers with identifiers
enum typeName {constant1, constant2…};
– Constants start at 0 (default), incremented by 1
– Unique constant names
– Example:
enum Status {CONTINUE, WON, LOST};
• Create an enumeration variable of type typeName
– Variable is constant, its value may not be reassigned
Status enumVar; // create variable
enumVar = WON; // set equal to WON
enumVar = 1; // ERROR
Example: A Game of Chance and
Introducing enum(II)
• Enumeration constants can have values pre-set
enum Months { JAN = 1, FEB, MAR, APR, MAY, JUN,
JUL, AUG, SEP, OCT, NOV, DEC};
– Starts at 1, increments by 1
• Craps simulator rules
– Roll two dice
• 7 or 11 on first throw, player wins
• 2, 3, or 12 on first throw, player loses
• 4, 5, 6, 8, 9, 10
– value becomes player's "point"
– player must roll his point before rolling 7 to win
3.10 Storage Classes
• Storage class specifiers
– Storage class
• Where object exists in memory
– Scope
• Where object is referenced in program
– Linkage
• Where an identifier is known
• Automatic storage
– Object created and destroyed within its block
– auto
• Default for local variables.
• Example:
auto float x, y;
– register
• Tries to put variables into high-speed registers
– Can only be used with local variables and parameters
Storage Classes

• Static storage
– Variables exist for entire program execution
– static
• Local variables defined in functions
• Keep value after function ends
• Only known in their own function
– Extern
• Default for global variables and functions.
• Known in any function
Scope Rules
• File scope
– Defined outside a function, known in all functions
– Examples include, global variables, function definitions and
functions prototypes
• Function scope
– Can only be referenced inside a function body
– Only labels (start:, case:, etc.)
• Block scope
– Declared inside a block. Begins at declaration, ends at }
– Variables, function parameters (local variables of function)
– Outer blocks “hidden” from inner blocks if same variable name
• Function prototype scope
– Identifiers in parameter list
– Names in function prototype optional, and can be used anywhere
References and Reference
Parameters
• Call by value
– Copy of data passed to function
– Changes to copy do not change original
– Used to prevent unwanted side effects
• Call by reference
– Function can directly access data
– Changes affect original
• Reference parameter alias for argument
– & is used to signify a reference
void change( int &variable )
{ variable += 3; }
– Adds 3 to the variable inputted
int y = &x.
– A change to y will now affect x as well
3.12 Recursion

• Recursive functions
– Are functions that calls themselves
– Can only solve a base case
– If not base case, the function breaks the problem into a
slightly smaller, slightly simpler, problem that resembles the
original problem and
• Launches a new copy of itself to work on the smaller problem,
slowly converging towards the base case
• Makes a call to itself inside the return statement
– Eventually the base case gets solved and then that value
works its way back up to solve the whole problem
Recursion

• Example: factorial
n! = n * ( n – 1 ) * ( n – 2 ) * … * 1
– Recursive relationship ( n! = n * ( n – 1 )! )
5! = 5 * 4!
4! = 4 * 3!…
– Base case (1! = 0! = 1)
The Fibonacci Series
• Fibonacci series: 0, 1, 1, 2, 3, 5, 8...
– Each number sum of two previous ones
– Example of a recursive formula:
fib(n) = fib(n-1) + fib(n-2)
• C++ code for fibonacci function

long fibonacci( long n )


{
if ( n == 0 || n == 1 ) // base case
return n;
else if ( n < 0 )
return –1;
else
return fibonacci( n - 1 ) + fibonacci( n – 2 );
}
The Fibonacci Series

• Diagram of Fibonnaci function

f( 3 )

return f( 2 ) + f( 1 )

return f( 1 ) + f( 0 ) return 1

return 1 return 0
3.14 Recursion vs. Iteration

• Repetition
– Iteration: explicit loop
– Recursion: repeated function calls
• Termination
– Iteration: loop condition fails
– Recursion: base case recognized
• Both can have infinite loops
• Balance between performance (iteration) and good software
engineering (recursion)
Functions with Empty Parameter Lists

• Empty parameter lists


– Either writing void or leaving a parameter list empty indicates
that the function takes no arguments
void print();
or
void print( void );
– Function print takes no arguments and returns no value
Inline Functions

• inline functions
– Reduce function-call overhead
– Asks the compiler to copy code into program instead of using a
function call
– Compiler can ignore inline
– Should be used with small, often-used functions
• Example:
inline double cube( const double s )
{ return s * s * s; }
3.18 Default Arguments

• If function parameter omitted, gets default value


– Can be constants, global variables, or function calls
– If not enough parameters specified, rightmost go to their
defaults
• Set defaults in function prototype
int defaultFunction( int x = 1,
int y = 2, int z = 3 );
3.19 Unary Scope Resolution Operator

• Unary scope resolution operator (::)


– Access global variables if a local variable has same name
– not needed if names are different
– instead of variable use ::variable
3.20 Function Overloading

• Function overloading
– Having functions with same name and different parameters
– Should perform similar tasks ( i.e., a function to square ints,
and function to square floats).
int square( int x) {return x * x;}
float square(float x) { return x * x; }
– Program chooses function by signature
• signature determined by function name and parameter types
– Can have the same return types

You might also like