Introduction To Functions
Introduction To Functions
Introduction to Functions
Semester 2, Session 2022/2023
Copy-paste coding
#include <iostream>
using namespace std;
Bad coding!!
int main() {
// To find the maximum between 3 and 4
int x = 3, y = 4;
int maxValue = x;// assume x is the largest to start
if (y > maxValue) { // determine whether y is greater than maxValue
maxValue = y; // make y the new maxValue
}
cout << "The maximum between 3 and 4 is " << maxValue << endl;
int main() {
cout << "The maximum between 3 and 4 is " << maximum(3, 4) << endl;
cout << "The maximum between 10 and 7 is " << maximum(10, 7) << endl;
return 0;
}
Why define your own functions?
• Divide and conquer
• construct the program from simple, small pieces or components.
Modularize the program into self-contained tasks.
• Avoid repeating codes
• It is easy to copy and paste, but hard to maintain and
synchronize all the copies.
• Software Reuse
• you can reuse the functions in other programs, by packaging
them into library codes.
Global functions
• Do not belong to a particular class
• Have function prototypes placed in header files
• Can be reused in any program that includes the header file and that
can link to the function’s object code
• There’s no need to create any objects before calling the function.
Example:
sqrt in <cmath> header file
sqrt(900.0)
Basics of using functions
1. At the beginning of your program, declare the function.
2. Somewhere in your program, define the function.
3. Other functions can then call the function.
include <iostream>
using namespace std;
Function
declaration int maximum (int x, int y) {
int maxValue = x;
if (y > maxValue) {
Function maxValue = y;
definition }
return maxValue;
}
int main() {
cout << "The maximum between 3 and 4 is "
<< maximum(3, 4) << endl;
return 0; Function
} invocation
1. Function declaration
• Also called function prototype
• Syntax:
return_type function_name (argument1, argument2, …)
Example:
int maximum (int num1, int num2)
int bar() {
return 3; int bar(); function
} prototype
int foo() {
ERROR – function return bar()*2;
Solution 2: use a
bar() hasn’t been }
function prototype;
declared yet
informs the compiler
you’ll implement it later int bar() {
return 3;
If a function is defined before it is invoked, then }
its definition also serves as the function’s
declaration – separate prototype is unnecessary
Functions with empty parameter lists
• In C++, an empty parameter list is specified by writing either void
or nothing at all in parentheses.
#include <iostream>
using namespace std;
int main() {
function1(); // call function1 with no arguments
function2(); // call function2 with no arguments
}
function1 uses an empty parameter list to
void function1() { specify that the function receives no arguments
cout << "function1 takes no arguments" << endl;
} function2 uses a void parameter list to
specify that the function receives no arguments
void function2(void){
cout << "function2 also takes no arguments" << endl;
}
Default argument
• It’s common for a program to invoke a function repeatedly with the
same argument value for a particular parameter. In such cases, you
can specify that such a parameter has a default argument, i.e., a
default value to be passed to that parameter.
• Default arguments must be the rightmost (trailing) arguments in a
function’s parameter list.
• Default arguments must be specified with the first occurrence of the
function name – typically, in the function prototype.
Example:
int boxVolume(int length = 1, int width = 1, int height = 1);
All three parameters (length, width and height) have been given
default values of 1.
Default argument (Example – 1/2)
#include <iostream>
using namespace std;
int main() {
// no arguments--use default values for all dimensions length = 1
cout << "The default box volume is: " << boxVolume(); width = 1
height = 1
// specify length; default width and height
cout << "\n\nThe volume of a box with length 10,\n" length = 10
<< "width 1 and height 1 is: " << boxVolume(10); width = 1
height = 1
// specify length and width; default height
cout << "\n\nThe volume of a box with length 10,\n" length = 10
<< "width 5 and height 1 is: " << boxVolume(10, 5); width = 5
height = 1
Default argument (Example – 2/2)
// specify all arguments
cout << "\n\nThe volume of a box with length 10,\n" length = 10
<< "width 5 and height 2 is: " << boxVolume(10, 5, 2) width = 5
<< endl; height = 2
} // end main
int main() {
cout << square(7) << endl; // calls int version
cout << square(7.5) << endl; // calls double version
}
C++ standard library header files
• The C++ Standard Library is divided into many portions, each with
its own header file.
• A header file “instructs” the compiler on how to interface with library
and user-written components
• The header files contain definitions of various class types and
functions, as well as constants needed by those functions.
Standard
Explanation
library header
<iostream> Contains function prototypes for the C++ standard input and
output
<iomanip> Contains function prototypes for stream manipulators that
format streams of data
<cmath> Contains function prototypes for math library functions
<fstream> Contains function prototypes for functions that perform input
from and output to files on disk
Case study: Random number generation
• The element of chance can be introduced into computer
applications by using the C++ Standard Library function rand.
• The function rand generates an unsigned integer between 0 and
RAND_MAX* (a symbolic constant defined in the <cstdlib>
header file).
• The function prototype for the rand function is in <cstdlib>.
• To produce integers in the range 0 to 5, we use the modulus
operator (%) with rand: rand() % 6 – This is called scaling.
• We can shift the range of numbers produced by adding a value. e.g.
1 + rand() % 6 produces integers in the range 1 to 6.
*
For GNU C++, the value of RAND_MAX is 2147483647; for Visual Studio, the value of RAND_MAX
is 32767.
Example: Rolling a six-sided die for 20
times
#include <iostream>
#include <iomanip>
#include <cstdlib> // contains function prototype for rand
int main() {
// loop 20 times
for (int counter = 1; counter <= 20; counter++) {
// pick random number from 1 to 6 and output it
cout << setw(10) << (1 + rand() % 6);
int main() {
int seed = 0; // stores the seed entered by the user
Note: Use only uppercase letters in the names of enumeration constants. This makes
these constants stand out in a program and reminds the programmer that enumeration
constants are not variables.
Introducing enum (Example – 1/2)
#include <iostream>
#include <cstdlib> // contains prototypes for functions srand and rand
#include <ctime> // contains prototype for function time
using namespace std; the constant CONTINUE has the value 0,
WON has the value 1 and LOST has the
int main() { value 2
// scoped enumeration with constants that represent the game status
enum Status {CONTINUE, WON, LOST}; // all caps in constants