1
C++ Programming I
Lecture 4
MIS160
Instructor – Larry Langellier
 2000 Prentice Hall, Inc. All rights reserved.
2
Lecture 4 - Functions
Outline
3.1
3.2
3.3
3.4
3.5
3.6
3.7
3.8
3.9
Introduction
Program Components in C++
Math Library Functions
Functions
Function Definitions
Function Prototypes
Header Files
Random Number Generation
Example: A Game of Chance and Introducing enum
 2000 Prentice Hall, Inc. All rights reserved.
3
Introduction
• Divide and conquer
– Construct a program from smaller pieces or components
– Each piece more manageable than the original program
 2000 Prentice Hall, Inc. All rights reserved.
4
Program Components in C++
• Programs written by
– combining new functions with “prepackaged” functions in
the C++ standard library.
– 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.
 2000 Prentice Hall, Inc. All rights reserved.
5
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
 2000 Prentice Hall, Inc. All rights reserved.
6
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
 2000 Prentice Hall, Inc. All rights reserved.
7
Math Library Functions
• Function arguments can be
– Constants
sqrt( 4 );
– Variables
sqrt( x );
– Expressions
sqrt( sqrt( x ) ) ;
sqrt( 3 - 6x );
 2000 Prentice Hall, Inc. All rights reserved.
8
Library Functions
• We’ve seen some library functions
already
• The declaration (prototype) for library
functions are contained in the include
file (like CONIO.H)
• The definitions for library functions
have already been compiled into a
library file (referenced by the include
file) which is “linked” in when you
compile your program
 2000 Prentice Hall, Inc. All rights reserved.
9
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
 2000 Prentice Hall, Inc. All rights reserved.
10
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;
}
 2000 Prentice Hall, Inc. All rights reserved.
11
Functions
• Example – table.cpp
• The Function Declaration
– In C++, names must be declared before they can be
used
– The Function Declaration is made up of three parts:
• The Return Type
• The Function Name
• The Parameter List
– Function Declarations are also called prototypes
• Calling the Function
– The name of the function followed by the argument
list (in parenthesis)
 2000 Prentice Hall, Inc. All rights reserved.
12
Functions
• The Function Definition (cont.)
– The body of the function is contained in braces
{}
– When a function is called, control passes to the
first statement of the body
– Control returns to the calling program when the
closing brace (}) is encountered
 2000 Prentice Hall, Inc. All rights reserved.
1
// Fig. 3.3: fig03_03.cpp
13
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Creating and using a programmer-defined function
#include <iostream>
1
4
Outline
1. Function prototype
using std::cout;
using std::endl;
int square( int );
Notice how parameters and return
value are declared.
2. Loop
// function prototype
int main()
{
for ( int x = 1; x <= 10; x++ )
cout << square( x ) << " ";
3. Function definition
cout << endl;
return 0;
}
// Function definition
int square( int y )
{
return y * y;
}
9
16
25
36
49
64
81
100
 2000 Prentice Hall, Inc. All rights reserved.
Program Output
1
// Fig. 3.4: fig03_04.cpp
2
// Finding the maximum of three integers
3
#include <iostream>
14
1. Function prototype
(3 parameters)
4
5
using std::cout;
6
using std::cin;
Outline
2. Input values
7 using std::endl;
2.1 Call function
8
9
int maximum( int, int, int );
// function prototype
10
11 int main()
12 {
13
int a, b, c;
14
15
cout << "Enter three integers: ";
16
cin >> a >> b >> c;
17
18
// a, b and c below are arguments to
19
// the maximum function call
20
cout << "Maximum is: " << maximum( a, b, c ) << endl;
 2000
Prentice Hall, Inc. All rights reserved.
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
15
return 0;
Outline
}
// Function maximum definition
// x, y and z below are parameters to
// the maximum function definition
int maximum( int x, int y, int z )
{
int max = x;
3. Function definition
if ( y > max )
max = y;
if ( z > max )
max = z;
return max;
}
Enter three integers: 22 85 17
Maximum is: 85
Enter three integers: 92 35 14
Maximum is: 92
Enter three integers: 45 19 98
Maximum is: 98
 2000 Prentice Hall, Inc. All rights reserved.
Program Output
16
Just Do It!
Write a function called hms_to_secs() that takes
three int values – for hours, minutes, and seconds – as
arguments, and returns the equivalent time in seconds
(type long). Create a program that exercises this
function by repeatedly obtaining a time value in hours,
minutes, and seconds from the user (format 12:59:59),
calling the function, and displaying the value of seconds
it returns.
 2000 Prentice Hall, Inc. All rights reserved.
17
Sample Pseudocode
main
Do
Input a time (12:59:59 format)
Convert to seconds -> call the function
Print the total
While hours, minutes and seconds are not zero
hms_to_secs(h, m, s)
Return (hours * 3600) + (minutes * 60) + seconds
 2000 Prentice Hall, Inc. All rights reserved.
18
Sample Solution
// hms_secs.cpp
#include <iostream>
using std cout; using std cin; using std endl;
long hms_to_secs(int h, int m, int s);
//declaration
int main()
{
int hours, minutes, seconds;
long totalsecs;
char dummy;
do {
cout << "\n\nEnter time (format 12:59:59)";
cout << "\n(0:0:0 to quit): ";
//get hrs, mins, secs
cin >> hours >> dummy >> minutes >> dummy >> seconds;
//call function
totalsecs = hms_to_secs(hours, minutes, seconds);
cout << "Seconds = " << totalsecs; //display seconds
} while( hours || minutes || seconds ); //quit if all zeros
cout << endl;
return 0;
}
 2000 Prentice Hall, Inc. All rights reserved.
19
Sample Solution
//-------------------------------------------------------------// function converts hms to secs
long hms_to_secs(int h, int m, int s)
{
// returns seconds
return static_cast<long>(h*3600) + m*60 + s;
}
 2000 Prentice Hall, Inc. All rights reserved.
20
Function Prototypes
• Function prototype
– Function name
– Parameters
• Information the function takes in
– 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
 2000 Prentice Hall, Inc. All rights reserved.
21
Passing Arguments to Functions
• An argument is a piece of data passed from a
program to the function
• Arguments allow the function to produce
different results depending on the values
passed to it
• Example – tablearg.cpp
• Passing constants
repchar(‘=‘, 23);
• When parameters are passed, their values are
automatically stored into the corresponding
parameters when the function is called
 2000 Prentice Hall, Inc. All rights reserved.
22
Passing Arguments to Functions
• Passing Variables
– Example – vararg.cpp
– The data type of the variables used as
arguments must match the parameter data types
in the function
– “by Value”
 2000 Prentice Hall, Inc. All rights reserved.
23
Returning Values from Functions
• When a function completes it can return a
single value
• So far we have seen a return type of void,
which means no return value
• Example – convert.cpp
• Provide the type of the return value in the
declaration and the definition
• Use the “return” function to return the value
• Always specify a return type for functions
• Example – convert2.cpp
 2000 Prentice Hall, Inc. All rights reserved.
24
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"
 2000 Prentice Hall, Inc. All rights reserved.
25
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
 2000 Prentice Hall, Inc. All rights reserved.
26
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
 2000 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Fig. 3.7: fig03_07.cpp
// Shifted, scaled integers produced by 1 + rand() % 6
#include <iostream>
27
Outline
1. Define loop
using std::cout;
using std::endl;
2. Output random
number
#include <iomanip>
using std::setw;
#include <cstdlib>
int main()
{
for ( int i = 1; i <= 20; i++ ) {
cout << setw( 10 ) << ( 1 + rand() % 6 );
Notice rand() % 6 . This returns a number
between 0 and 5 (scaling). Add 1 to get a
number between 1 and 6.
if ( i % 5 == 0 )
cout << endl;
}
return 0;
Executing the program again gives the
same "random" dice rolls.
}
5
2
5
5
5
4
3
1
3
2
2
4
 2000 Prentice Hall, Inc. All rights reserved.
5
5
2
6
5
5
1
4
Program Output
28
•
•
•
•
•
•
•
Aligning Output in Columns
The setw Manipulator is used to set the width of
output fields and is used to align output fields into
columns
Used with the insertion (<<) operator and cout
Only has an effect on the next item output with cout
The number (or string) that follows is right justified
within a field n characters wide
Example
cout << setw(8) << “Name”;
Most manipulators (except endl) are located in the
iomanip library
Examples - width1.cpp and width2.cpp
– Notice the cascaded insertion operators
 2000 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Fig. 3.9: fig03_09.cpp
// Randomizing die-rolling program
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
29
Outline
1. Initialize seed
2. Input value for seed
#include <iomanip>
using std::setw;
2.1 Use srand to
change random
sequence
#include <cstdlib>
int main()
{
unsigned seed;
cout << "Enter seed: ";
cin >> seed;
srand( seed );
for ( int i = 1; i <= 10; i++ ) {
cout << setw( 10 ) << 1 + rand() % 6;
if ( i % 5 == 0 )
cout << endl;
}
return 0;

} 2000 Prentice Hall, Inc. All rights reserved.
2.2 Define Loop
3. Generate and
output random
numbers
Enter seed: 67
1
5
6
6
5
3
1
1
4
2
Enter seed: 432
4
2
2
5
6
1
4
4
3
4
Enter seed: 67
1
5
6
6
5
3
1
1
4
2
Notice how the die rolls
change with the seed.
 2000 Prentice Hall, Inc. All rights reserved.
30
Outline
Program Output
31
Just Do It!
Write a program that plays the game of “guess the number” as follows: Your
program chooses the number to be guessed by selecting an integer at random
in the range 1 to 1000. The program then types:
I have a number between 1 and 1000.
Can you guess my number?
The player then types a first guess. The program responds with one of the
following:
1. Excellent! You guessed the number!
2. Too low. Try again.
3. Too high. Try again.
If the player’s guess is incorrect, your program should loop until the player
finally gets the number right. Your program should keep telling the player
Too high or Too low to help the player “zero in” on the correct answer.
• Please implement and use two functions
– generateAnswer() and isCorrect()
 2000 Prentice Hall, Inc. All rights reserved.
32
Pseudocode Sample
While the user would like to continue playing
Generate a random answer
Prompt the user for a guess
While the user’s guess is incorrect
Give a hint (Too low, Too high)
Accept another guess
Congratulate the user and ask if they’d like to play
again
 2000 Prentice Hall, Inc. All rights reserved.
33
Sample Solution
#include <iostream>
#include <cstdlib>
#include <ctime>
using std cout; using std cin; using std endl;
int generateAnswer()
{
srand( time( 0 ) );
return ( 1 + rand() % 1000 );
}
bool isCorrect( int g, int a )
{
if ( g == a )
return true;
if ( g < a )
cout << "Too low. Try again.\n? ";
else
cout << "Too high. Try again.\n? ";
return false;
}
 2000 Prentice Hall, Inc. All rights reserved.
34
Sample Solution
int main()
{
int answer, guess;
char response;
do {
answer = generateAnswer();
cout << "\nI have a number between 1 and 1000.\n"
<< "Can you guess my number?\nPlease type your"
<< " first guess.\n? ";
cin >> guess;
while ( !isCorrect( guess, answer ) )
cin >> guess;
cout << "\nExcellent! You guessed the number!\n"
<< "Would you like to play again?\nPlease type (y/n)? ";
cin >> response;
} while ( response == 'y' );
return 0;
}
 2000 Prentice Hall, Inc. All rights reserved.
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;
enumVar = WON;
enumVar = 1;
 2000 Prentice Hall, Inc. All rights reserved.
// create variable
// set equal to WON
// ERROR
35
36
Enumerations
• Allows you to declare a new data type with a
finite (and known) set of possible values
• Syntax
enum enumName {eVal1, eVal2, eVal3, …}
• The enum declaration must define ALL
possible values
• Defining an enum variable
enumName varName;
• Example – dayenum.cpp
 2000 Prentice Hall, Inc. All rights reserved.
37
Enumerations
• Enumerations are treated internally as
integers, typically starting at 0 and
incrementing to the right
• As a result, you can use arithmetic and
relational operators with enum values
• Examples – wdcount.cpp and
cardenum.cpp
 2000 Prentice Hall, Inc. All rights reserved.
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
 2000 Prentice Hall, Inc. All rights reserved.
38
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Fig. 3.10: fig03_10.cpp
// Craps
#include <iostream>
39
Outline
1. rollDice
prototype
using std::cout;
using std::endl;
#include <cstdlib>
1.1 Initialize variables
and enum
#include <ctime>
using std::time;
1.2 Seed srand
int rollDice( void );
// function prototype
int main()
{
enum Status { CONTINUE, WON, LOST };
int sum, myPoint;
Status gameStatus;
srand( time( 0 ) );
sum = rollDice();
Notice how the
enum is defined
// first roll of the dice
switch ( sum ) {
case 7:
case 11:
// win on first roll
gameStatus = WON;
break;
case 2:
case 3:
case 12:
// lose on first roll
gameStatus = LOST;
break;
 2000 Prentice Hall, Inc. All rights reserved.
2. Define switch
statement for
win/loss/continue
35
default:
// remember point
Outline
36
gameStatus = CONTINUE;
37
myPoint = sum;
38
cout << "Point is " << myPoint << endl;
39
break;
40
// optional
2.2 Print win/loss
while ( gameStatus == CONTINUE ) {
43
// keep rolling
sum = rollDice();
44
45
if ( sum == myPoint )
46
// win by making point
gameStatus = WON;
47
else
48
if ( sum == 7 )
49
50
// lose by rolling 7
gameStatus = LOST;
}
51
52
53
54
55
if ( gameStatus == WON )
cout << "Player wins" << endl;
else
cout << "Player loses" << endl;
56
57
2.1 Define loop to
continue playing
}
41
42
40
return 0;
58 }
59  2000 Prentice Hall, Inc. All rights reserved.
60 int rollDice( void )
61 {
62
int die1, die2, workSum;
63
64
die1 = 1 + rand() % 6;
65
die2 = 1 + rand() % 6;
66
workSum = die1 + die2;
67
cout << "Player rolled " << die1 << " + " << die2
68
<< " = " << workSum << endl;
69
70
return workSum;
71 }
Player rolled 6 + 5 = 11
Player wins
Player rolled 6 + 5 = 11
Player wins
Player rolled
Point is 10
Player rolled
Player rolled
Player rolled
Player rolled
Player wins
4 + 6 = 10
2
6
3
6
+
+
+
+
4
5
3
4
=
=
=
=
6
11
6
10
Player rolled 1 + 3 = 4
Point is 4
Player rolled 1 + 4 = 5
Player rolled 5 + 4 = 9
Player rolled 4 + 6 = 10
Player rolled 6 + 3 = 9
Player rolled 1 + 2 = 3
Player rolled 5 + 2 = 7
Player loses
 2000 Prentice Hall, Inc. All rights reserved.
41
Outline
3. Define rollDice
function
Program Output
42
Just Do It!
The previous example program is available in craps.cpp.
Modify this program to allow wagering. Initialize variable
bankBalance to 1000 dollars. Prompt the player to enter a
wager. Use a while loop to check that wager is less than or
equal to bankBalance and , if not, prompt the user to reenter
wager until a valid wager is entered. After a correct wager
is entered, run one game of craps. If the player wins,
increase bankBalance by wager and print the new
bankBalance. If the player loses, decrease bankBalance by
wager, print the new bankBalance, check on whether
bankBalance has become zero and, if so, print the message
“Sorry. You busted!”
 2000 Prentice Hall, Inc. All rights reserved.
43
Sample Solution
int main()
{
int result, wager = 0, bankBalance = 1000;
char playAgain;
srand( time( 0 ) );
do {
cout << "You have $" << bankBalance
<< " in the bank.\nPlace your wager: ";
cin >> wager;
while ( wager <= 0 || wager > bankBalance ) {
cout << "Please bet a valid amount.\n";
cin >> wager;
}
result = craps();
 2000 Prentice Hall, Inc. All rights reserved.
44
Sample Solution (cont.)
if ( result == LOST ) {
bankBalance -= wager;
cout << "Your new bank balance is $" << bankBalance << "\n";
if ( bankBalance == 0 ) {
cout << "Sorry. You Busted! Thank You For Playing.\n";
break;
}
}
else {
bankBalance += wager;
cout << "Your new bank balance is $" << bankBalance << "\n";
}
cout << "Would you like to try your luck again (y/n)? ";
cin >> playAgain;
} while ( playAgain == 'y' || playAgain == 'Y' );
cout << endl;
return 0;
}
 2000 Prentice Hall, Inc. All rights reserved.