Review Topics
General Information
Housekeeping
- Make sure you follow along with this page linked in Canvas
- Please keep your microphone off unless you are asking a question
- Please turn on camera if you can (optional)
- Use chat if you would like to comment or ask questions
Announcements
- If you have problems compiling this code:
#include
#include
using namespace std;
int main() {
vector temp = { 12.3, 23.4, 34.5, 45.6, 56.7 };
return 0;
}
to compile a vector with this approach you must use C++ 11 or later
g++ -Wall -Wextra -Wpedantic -std=c++11 -o main main.cpp
- Notice that Replit in its compiling uses -std=c++17
clang++-7 -pthread -std=c++17 -o main main.cpp
- Thus you will not have any problems on replit but may if you compile elsewhere
- Spring Break is next week
- STEM Center drop in tutoring in Computer Science open during Spring Break:
Sat (3/20) 1 pm - 5 pm
Mon - Thurs (3/22 - 3/25) 5 pm - 7 pm
Fri (3/26) 1 pm - 7 pm
Sat (3/27) 1 pm - 5 pm
- Cabrillo College will now allow students to select the P/NP option by the grade deadline for the term--ends in December
- Remember that PAs and the Individual Readiness Assurance Quiz are due before class on Tuesday.
- Remember to post in the Pair programming partners discussion group if you need a partner
- Remember that the exercises from this page are due Sunday at 9:00pm.
- Remember that CAs, Labs, and Class Exercises may be completed up to two days late but with a 10%/day penalty.
- Remember that some lab solutions are posted in Canvas Modules
- Free Fresh Market schedule: free fresh fruits and vegetables
- Food & Housing Resources: free food, meals, temporary and permanent housing
- COVID-19 Resources and Information: Includes loaner-laptop information
- Campus WiFi Access
- Aptos: Parking lots K and L on this Cabrillo Aptos Map
- Watsonville: Parking lot at Watsonville Center
Homework Help
^ top
8.1: Readiness Assessment Quizzes
- Reading and participation activities are due before the first class meeting of the week
- Quizzes assess the comprehension of the reading and participation activities
Quiz Part 1: Individual Readiness Assessment
- Complete this quiz solo to assess your reading comprehension and readiness
- Must take this quiz before the first class meeting of the week to ensure you are ready for the team quiz
- Quiz is open book and notes but timed
- Highest score is counted so take the quiz multiple times
Quiz Part 2: Team Readiness Assessment (20m)
- Must attend the class meeting to take this quiz
- Login to Canvas
- Will move to breakout rooms with your team
- Make sure you have the access code for the exam
- Openly discuss what you believe to be the best answers for the questions
- Decide how to agree on the answers
- Strive to reach a consensus on quiz answers
- If no consensus, work it out as you and others in your group see fit
- Turn in the quiz as a group
- Each group member will receive the same score
- Return to the main meeting room when finished
Quiz Appeals
- After completing the team quiz, team members may appeal an answer
- Appeals can be based on two criteria:
- Question is factually wrong
Appeal must included citations to sources of information that document or support an alternative answer. Team may access reference materials during the appeal.
- Question is confusing based on it's wording
Appeal must include an appropriate rewrite of questions or answers that you interpret as ambiguous or confusing.
- Work with teammates to develop and write any appeals
- Team has up to 24 hours after the quiz to email appeal to instructor
- If appeal is granted, only the teams that submitted appeal gets credit
^ top
8.2: Function basics
8.2.1: Reviewing function basics
Defining Functions
Example Function Definitions
#include <iostream>
using namespace std;
void ShowFToC(double fDegrees) {
double cDegrees = 5.0 / 9 * (fDegrees - 32);
cout << fDegrees << " degrees Fahrenheit is "
<< cDegrees << " degrees Celsius." << endl;
return;
}
int main() {
double fTemperature;
cout << "Enter a temperature in Fahrenheit: ";
cin >> fTemperature;
ShowFToC(fTemperature);
return 0;
}
Parameters
- In the parenthesis of the function definition are the parameters
- Parameters are the inputs to a function
- When we define a function, we want it to be reusable
- To make a function reusable, we avoid hard-coding important values
- Instead, we pass the key values by defining parameter variables
- When we call the function, we supply an argument for any parameter
^ top
Exercise 8.2: Coding function basics (15m)
In this exercise we write function definitions with parameters.
Remember to verify your code by compiling after each step.
For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.
Specifications
- Start Repl.it and copy the following code into the code editor.
#include <iostream>
using namespace std;
//Function definition goes here
int main() {
int length = 1;
do {
cout << "\nI will print squares for you!\n";
cout << "Enter the length of a side (-1 to quit): ";
cin >> length;
//code to call function
} while (length > 0);
cout << "Thanks for \"squaring\" with me!" << endl;
return 0;
}
- Compile and run your code to make sure you added the code correctly.
When you run the program, the output should look like:
I will print squares for you!
Enter the length of a side (-1 to quit): 5
I will print squares for you!
Enter the length of a side (-1 to quit): -1
Thanks for "squaring" with me!
- Write a function that prints squares named
printSquares() with an int parameter named size that returns nothing.
Use the following code inside the function.
for (int row = 1; row <= size; row++)
{
for (int col = 1; col <= size; col++)
{
cout << "*";
}
cout << endl; // newline before next row
}
- Call your function inside the
while loop so that it will print out a square given the user input for the length of a side.
- Run the program again and verify you see results like the following:
I will print squares for you!
Enter the length of a side (-1 to quit): 5
*****
*****
*****
*****
*****
I will print squares for you!
Enter the length of a side (-1 to quit): -1
Thanks for "squaring" with me!
- Once satisfied with your code, copy it into a text editor, save the file as "
squarefun.cpp ", and submit the file to Canvas with the rest of the exercise files for the week.
When finished developing your code click here to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.
Example Completed Program
#include <iostream>
using namespace std;
void printSquares(int size) {
for (int row = 1; row <= size; row++) {
for (int col = 1; col <= size; col++) {
cout << "*";
}
cout << endl; // newline before next row
}
}
int main() {
int length = 1;
do {
cout << "\nI will print squares for you!\n";
cout << "Enter the size of a side (-1 to quit): ";
cin >> length;
printSquares(length);
} while (length > 0);
cout << "Thanks for \"squaring\" with me!" << endl;
return 0;
}
^ top
8.3: Return
8.3.1: Reviewing return
- The first word in the function signature is the return type
int add(int a, int b)
- The return type specifies the type of data the function outputs
- In the example above the return type is an
int
- A function may return one value using a return statement
Example Code
#include <iostream>
using namespace std;
int add(int a, int b) {
int sum = a + b;
return sum;
}
int main() {
cout << "Enter two numbers to add: ";
int num1, num2;
cin >> num1 >> num2;
int total = add(num1, num2);
cout << "Sum=" << total << endl;
return 0;
}
Return Statement
- Functions that return a value must execute a
return statement
return result;
- The following function
add() has a return statement:
int add(int a, int b) {
int sum = a + b;
return sum;
}
- Note that the type of the returned valued must be compatible with the function return type
- The returned value is substituted for the function call in the calling code
sum =>[replaces]=> add(num1, num2)
- We must save the returned value if we want to process it later in the program
int total = add(num1, num2);
Returning a Value from a Function
Returning an Expression
- The value after the word
return can be an expression
- We could rewrite our
return statement to the following:
return a + b;
^ top
Exercise 8.3: Coding return (12m)
In this exercise we code a function with a return statement.
For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.
Specifications
- Start Repl.it and copy the following code into the code editor.
#include <iostream>
using namespace std;
// Define function here
int main() {
// Enter your code here
return 0;
}
- Write the definition of a function named
sub that receives two int numbers and returns an int value, like the add() function.
returnType sub(two_int_parameters)
- Add a pair of curly braces for the function body:
{ } .
- Inside the function body, subtract the second parameter from the first and return the value.
- Compile and run your code. What do you see when you compile and run? (click here)
The program should compile but will not display a value until we write a function call and cout statements, which we will do next.
- Inside the
main() function, add these statements:
cout << "Enter two numbers to subtract: ";
int num1, num2;
cin >> num1 >> num2;
int diff = sub(num1, num2);
cout << "Difference=" << diff << endl;
- Compile and run your program and verify the output looks like:
Enter two numbers to subtract: 3 1
Difference=2
- Once satisfied with your code, copy your code into a text editor, save the file as "
sub.cpp ", and submit the file to Canvas with the rest of the exercise files for the week.
When finished developing your code click here to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.
Example Completed Program
#include <iostream>
using namespace std;
int sub(int a, int b) {
int sum = a - b;
return sum;
}
int main() {
cout << "Enter two numbers to subtract: ";
int num1, num2;
cin >> num1 >> num2;
int diff = sub(num1, num2);
cout << "Difference=" << diff << endl;
return 0;
}
^ top
8.4: Reasons for defining functions
There are many reasons for developing functions including:
- Breaking up long sequnces of code into more easily understandable pieces
- Developing a program incrementally--in smaller pieces
- Avoiding redundant code
8.4.1: Reviewing reasons for defining functions
Incremental development
- In addition to more easily understanding code, functions also help in developing programs
- Funtions allow us to divide a program into separate modules that can be developed and tested separately and then integrated into a single program
- Functions also allow programmers to develop code incrementally
- Incremental development is where a program is designed, implemented and tested incrementally (a little more is added each time) until finished
Function Stubs
Example Function Stub
double calcUnitPrice (int diameter, double price) {
cout << "FIXME: Calculate unit price" << endl;
return 1; // dummy value
}
Avoiding Redundant Code
- A function can be defined once and called from many places in a program
- Repeating the same code over and over is known as redundant code
- Unnecessary repeated (redundant) code should be avoided in programming
- One way to avoid repeating the same code over and over is to put the code in a function
^ top
Exercise 8.4: Simplifying code with functions (20m)
In this exercise we simplify code using functions.
For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, choose one member to show your solution to the class by sharing your screen. The instructor will ask one teams to share their solution.
Bonus to the team with the least number of lines of code that follows good style (Zybook 2.14) including:
- Each statement usually appears on its own line.
- A blank line separates conceptually distinct groups of statements, but related statements usually have no blank lines between them.
- Most items are separated by one space (and not less or more). No space precedes an ending semicolon.
- Sub-statements indented 3 or 4 spaces from parent statement.
- Braces always used even if only one sub-statement, like in: if, for, while, and do-while.
- Closing brace
} on its own line, except else can be: } else {
- Lines of code are usually less than 80 characters wide.
Specifications
- Start Repl.it and copy the following code into the code editor.
#include <iostream>
using namespace std;
int main() {
double powerConsumptionApp1;
double powerConsumptionApp2;
double powerConsumptionApp3;
double hoursOfUse1;
double hoursOfUse2;
double hoursOfUse3;
double energyPerDay1;
double energyPerDay2;
double energyPerDay3;
double totalEnergyConsumed;
powerConsumptionApp1 = 600.85;
hoursOfUse1 = 12.8;
energyPerDay1 = (powerConsumptionApp1 * hoursOfUse1) / 1000;
powerConsumptionApp2 = 1800.45;
hoursOfUse2 = 0.45;
energyPerDay2 = (powerConsumptionApp2 * hoursOfUse2) / 1000;
powerConsumptionApp3 = 70;
hoursOfUse3 = 1.5;
energyPerDay3 = (powerConsumptionApp3 * hoursOfUse3) / 1000;
totalEnergyConsumed = energyPerDay1 + energyPerDay2 + energyPerDay3;
cout << "The total energy consumed per day is "
<< totalEnergyConsumed
<< "." << endl;
return 0;
}
- Compile your code to make sure it has correct syntax. Run the code and verify you see the following output.
The total energy consumed per day is 8.60608.
- Before
main() , add the following function.
double ComputeEnergyConsumed(double power, double hours) {
return (power * hours) / 1000;
}
- Using the above function, simplify your program from 35 lines of code to less than 25 lines (20 is easily possible), while keeping the same output and following good programming style like blank lines (5 minimum) around functions and other areas of code. Magic numbers are allowed in this exercise since the original code has magic numbers.
Bonus to the team with the least number of lines of code that follows good style.
- Once satisfied with your code, copy your code into a text editor, save the file as "
simple.cpp ", and submit the file to Canvas with the rest of the exercise files for the week.
When finished developing your code click here to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.
Example Completed Program
#include <iostream>
using namespace std;
double ComputeEnergyConsumed(double power, double hours) {
return (power * hours) / 1000;
}
int main() {
double energyPerDay1;
double energyPerDay2;
double energyPerDay3;
double totalEnergyConsumed;
energyPerDay1 = ComputeEnergyConsumed(600.85, 12.8);
energyPerDay2 = ComputeEnergyConsumed(1800.45, 0.45);
energyPerDay3 = ComputeEnergyConsumed(70, 1.5);
totalEnergyConsumed = energyPerDay1 + energyPerDay2 + energyPerDay3;
cout << "The total energy consumed per day is "
<< totalEnergyConsumed
<< "." << endl;
return 0;
}
^ top
8.5: Function flow
8.5.1: Reviewing function flow
- Flow of control (or control flow) refers to the order in which programs execute instructions
- By default, code executes sequentially: one statement after another from top to bottom in a function like
main()
- We have changed the flow of control using if-statements and loops
- Functions also change the flow of control through function calls
- When code reaches a function call, the current function (like
main() ) stops executing and transfers control to the called function
- When the called function returns, control is passed back to the calling function
Flow of control for a function call
Function Call Flow
- Every program starts executing at the start of the function
main() .
- When reaching a function call, arguments are copied to the parameters.
- Function code executes until reaching a return statement.
- Return statement returns a value to the function call.
- Calling function continues after the function returns.
Tracing Code
- One critical programming skill is tracing program code, often statement by statement
- In a sense, we have to "be the computer"

- To trace the code, we follow the flow of execution
- Every program starts with the first line of the
main() function and continues sequentially statement by statement from there
- A function call transfers the flow to the first statement of the called function
- When the function returns, the flow transfers back to the point from which the call was made
- Thus, every time the flow of control reaches a function call, the program:
- Temporarily stops executing in the current function
- Jumps to the called function and executes the statements of that function
- Returns to the point in the code from which it jumped
- Let us trace the flow in the following code by line number:
Example Code with Function Call
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
#include <iostream>
using namespace std;
int add(int a, int b) {
int sum = a + b;
return sum;
}
int main() {
cout << "Enter two numbers to add: ";
int num1, num2;
cin >> num1 >> num2;
int total = add(num1, num2);
cout << "Sum=" << total << endl;
return 0;
}
|
^ top
Exercise 8.5: Tracing flow (10m)
 Be the computer
In this exercise we trace the flow of control when in a program with a function call.
For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.
Specifications
- Create a text file named
trace.txt .
- In the
trace.txt file, list the line numbers of each statement of the following program in the order the lines are executed. For example, if main() starts on line 9, statements are executed as follows:
9, 10, 11, 12, ...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
#include <iostream>
using namespace std;
int add(int a, int b) {
int sum = a + b;
return sum;
}
int main() {
cout << "Enter two numbers to add: ";
int num1, num2;
cin >> num1 >> num2;
int total = add(num1, num2);
cout << "Sum=" << total << endl;
return 0;
}
|
Do not bother to list blank lines or lines containing only a curly brace (} ) of a function definition.
- Review the code trace with another student in the class. Then add a comment to the top of the trace.txt file that contains the name of the team members with whom you reviewed the code, like:
Reviewed trace with team members: Fred George, ...
- Save the trace.txt to submit to Canvas with the rest of the exercise files for the week.
When finished with your trace click here to verify.
Reviewed with team members: Fred George, Bob Bobson, and Jon Jonson
9, 10, 11, 12, 13, 4, 5, 6, 13, 14, 16
Alternatively:
9-13
4-6
13-16
^ top
8.6: Scope
8.6.1: Reviewing variable scope
- Functions are self-contained units, having all that is needed within themselves
- A variable declared inside a function can only be used within that function
Local variable: a variable that can only be accessed within a function or block.
- Parameters are a type of local variable and thus can only be used inside the function in which they are declared
- As an example of a local variable, we declared
sum inside the add() function:
int sum = a + b;
- In addition, we declared another variable named
total inside main() :
int total = add(num1, num2);
- These variables cannot be accessed outside the function they were declared
Scope
Passing Arguments to Function Parameters
Example code with variables in different scopes
#include <iostream>
using namespace std;
const double PI = 3.14159265;
double circleArea(double radius) {
double area = PI * radius * radius;
return area;
}
int main() {
cout << "Enter the radius of a circle: ";
double radius = 0.0;
cin >> radius;
double area = circleArea(radius);
cout << "The circle area is " << area << endl;
return 0;
}
Global Variables and Constants
Programming Style: No Global Variables
- Global variables are variables that are defined outside functions
- They are declared just like a global constant but without the
const keyword
- Unlike global constants, global variables are considered very poor programming practice
- A global variable can be modified anywhere in your program, so it is hard to trace where it changes
- Local variables always have precedence over global variables
- Global variables make programs more difficult to understand and maintain
- Do not use global variables in your programs for this course
- Instead, use function parameters and return statements to transfer data from one function to another
^ top
Exercise 8.6a: Exploring global variables (10m)
In this exercise we examine some of the hazards of using global variables.
For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, choose one member to explain your solution to the class by sharing your screen. The instructor will ask one team to share their solution.
Specifications
- Create a text file named
globalout.txt .
- Look at the following code without running it.
int x, y, z;
int fun(int a, int b) {
y = 42;
int x;
x = a + 2;
a = a * 3;
b = x + a;
return b;
}
int main( ) {
x = 1;
int y = 2;
z = 3;
y = fun(y, x);
cout << x << ' ' << y << ' ' << z << endl;
return 0;
}
Assume that the code exceutes despite not having iostream, etc.
- As a team, trace the code and decide on the output of the code without running it.
- Type the expected output into the
gobalout.txt file.
- Save the globalout.txt file to submit to Canvas with the rest of the exercise files for the week.
^ top
8.6.2: Reviewing function prototypes
- C++ allows us to declare functions without defining them
- A declaration introduces identifiers (names) into a C++ program without allocating memory
- Function declarations (prototypes) have the function heading without the function body
- The general syntax for declaring a function is:
returnType functionName(parameter1, ..., parametern);
- Where:
- returnType: the type of the value returned
- functionName: the name you make up for the function
- parameterx: the input values, if any
- As an example, we can declare a function to calculate the square of a number like this:
double square(double number);
- Commonly, a programmer wishes to have the
main() definition appear near the top of a file
- Other functions then appear below
main()
- This allows people reading the code to see
main() first
- By declaring the function prototype before
main() , people see the main() function definition first
- By declaring a function, the compiler can resolve a function call made inside
main()
- Thus, we can reorganize our programs to place function definitions after
main()
- We can see this new function organization in the following example
Example Code
#include <iostream>
using namespace std;
// Returns the square of a number
double square(double number);
// Displays a message to the console
void log(string funName, double value);
int main() {
double number = 5;
log("main", number);
double result = square(5);
log("main", result);
return 0;
}
double square(double number) {
log("square", number);
double result = number * number;
log("square", result);
return result;
}
void log(string funName, double value) {
cout << "In " << funName << "() the value is ";
cout << value << endl;
}
^ top
Exercise 8.6b: Coding function prototypes (10m)
In this exercise we add function prototypes to a program.
For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.
Specifications
- Start Repl.it and copy the following code into the code editor.
#include <iostream>
using namespace std;
int FunA(int num) {
if (num > 0) {
FunB(--num);
}
return 42;
}
int FunB(int param) {
return FunA(--param);
}
int main() {
int num = FunA(3);
cout << num << endl;
return 0;
}
- Compile and run the code to see the error produced.
- Add function declarations (function prototypes) to resolve the errors.
- After resolving the error, reverse the order of
FunA() and FunB() and compile again.
- Add function declarations (function prototypes) to resolve the errors, if any.
- Move
FunA() and FunB() below main() and compile again.
- Add function declarations (function prototypes) to resolve the errors, if any.
- Once satisfied your code will work when defining functions after
main() , copy your code into a text editor, save the file as "proto.cpp ", and submit the file to Canvas with the rest of the exercise files for the week.
When finished developing your code click here to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.
Example Completed Program
#include <iostream>
using namespace std;
int FunA(int param);
int FunB(int param);
int main() {
int num = FunA(3);
cout << num << endl;
return 0;
}
int FunA(int num) {
if (num > 0) {
FunB(--num);
}
return 42;
}
int FunB(int param) {
return FunA(--param);
}
^ top
8.7: Random numbers
Random numbers are a series of numbers whose future values cannot be predicted.
8.7.1: Reviewing random numbers
Psuedorandom
- The numbers produced by the library appear to be random but are not
- We call these types of random numbers psuedorandom
- Psuedorandom means that given an initial starting condition, the procedure always produces the same result
- Random numbers actually come from a a very long sequence of numbers computed from fairly simple formulas; they just behave like random numbers
- The following program uses
rand() to produce the same output every time it runs
- The reason that the numbers are the same is because the numbers are generated with the same computer commands every time it is called
- When running the following program, remember the first few numbers and then start the program again
- Notice that the same sequence of numbers is produced
Example Program Using rand()
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int i;
for (i = 0; i < 10; i++) {
int num = rand();
cout << num << "\n";
}
return 0;
}
|
More information
Check Yourself
- A number whose value cannot be predicted ahead of time is known as a ________ number.
- The problem with this random number generator from xkcd is that ________.
- dice rolling is not a fair way to get random numbers
- it was not selected randomly
- you can predict the number ahead of time
- nothing is wrong
- The function
rand() returns a number between ________ and including ________.
^ top
8.7.2: Seeding the Random Generator
- When running programs we do not always want the same sequence of numbers every time
- For instance, if we run a dice simulation for a game we want different numbers every time the program runs
- To get a different number, we must "seed" the random number generator
- We set the seed with the
srand() function with the syntax:
srand(seed)
- Where:
- seed: the initial number for the random sequence
- For example:
randomSeed(seed);
- If we change the
seed value, we will get different numbers every time
Changing the Starting Value
- One common strategy for changing the seed value is to use the current time
- Since the time changes every second, we get a new random number sequence every time we run our program
- To generate a number from time, we use the time() function from the standard time library:
srand(time(0));
- The expression
time(0) returns the number of seconds since January 1, 1970
- To make use of the
time() function we may need to include the library:
#include <ctime>
- We call
srand(time(0)) only once in a program or we may get repeated numbers
Example Program Using srand()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
srand(time(0));
int i;
for (i = 0; i < 10; i++) {
int num = rand();
cout << num << "\n";
}
return 0;
}
|
Check Yourself
- The function that sets the starting location, or seed, for
rand() is ________.
- To produce a new random number sequence every time a program starts use the code: ________.
- True or false: you must reseed the random number generator every time before calling
rand() .
^ top
Exercise 8.7: Getting Random (10m)
In this exercise we explore how to generate random numbers.
To develop the code, we break into teams. Within the team, work with each other to develop a solution. When the team has finished, Choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.
Specifications
- Start Repl.it and copy the following program into a text editor.
#include <iostream>
using namespace std;
int main() {
// Enter your code here
return 0;
}
- Compile and run the starter program to make sure you entered it correctly.
No output is expected when run.
- Add the library
cstdlib at the top of the file:
#include <cstdlib>
For some C++ compilers you may need to add the ctime library:
#include <ctime>
- We generate random numbers by using the
rand() function. Declare two integer variables, die1 and die2 , and assign them values returned by the rand() function using code like the following:
int die1 = rand();
int die2 = rand();
cout << "You rolled a " << die1
<< " and a " << die2 << endl;
- Compile and run your program and make sure your output looks like the following. Note that the actual numbers may be different.
You rolled a 1804289383 and a 846930886
Notice the size of the numbers displayed. We want to limit the size of the random numbers generated by rand() to only six numbers. We limit the range by using the modulus (% ) operator.
- Change the two assignment statements with the following code:
int die1 = rand() % 6 + 1;
int die2 = rand() % 6 + 1;
The number 6 in the above code is known as the scaling factor since it limits the scale of the numbers produced by the rand() function to a range. The + 1 shifts the range from 0...5 to 1...6.
- Compile and run your program and make sure your output looks like the following. Note that the actual numbers may be different.
You rolled a 1 and a 4
- Rerun your code two or more times and check the numbers rolled. Do you see any patterns? To correct the problem we must "seed" the random number generator. Add the following code after the start of main and before your
rand() statements:
srand(time(0));
- Rerun your code a few more times and check the numbers rolled. Once satisfied with your code, copy your code into a text editor, save the file as "
dice.cpp ", and submit the file to Canvas with the rest of the exercise files for the week.
When finished developing your code click here to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.
Example Completed Program
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
srand(time(0));
int die1 = rand() % 6 + 1;
int die2 = rand() % 6 + 1;
cout << "You rolled a " << die1
<< " and a " << die2 << endl;
return 0;
}
^ top
Last Updated: April 06 2021 @03:27:40
|