8. Functions

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

See Announcements link in Canvas to keep up with what is going on. Here are a few other items:

  • Complete vacinations required to visit campus or sign up for future terms (instructions)
  • 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 CAs and 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
  • Food & Housing Resources: free food, meals, temporary and permanent housing
  • COVID-19 Resources and Information: Includes loaner-laptop information
  • Campus WiFi Access
  • Extra credit bonus points for the first student to report a problem

Homework Help

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
  • Cannot take the quiz late
  • 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 and enter the access code
  • 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:
    1. 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.

    2. 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

8.2: Function basics

8.2.1: Reviewing function basics

  • As we add more code to main(), it becomes too long to easily understand
  • A solution is to break up the long sequences of code into shorter sections using functions

    Function: a named block of statements that can receive input, perform an action, and optionally return a value

  • Functions allow us to organize code into short reusable pieces
  • Creating functions is like adding new commands to the programming language

Defining Functions

  • To define a function, we use the following syntax:
    returnType functionName(parameter1, ..., parametern) {
        statements
    }
    
  • Where:
    • returnType: the data type of the value returned
    • functionName: the name you make up for the function
    • parameterx: the input values, if any
    • statements: the list of statements to execute when the function is called
  • The following example contains two function definitions

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

Exercise 8.2: Coding function basics (10m)

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, return to the main room.

Specifications

  1. Start Replit 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;
    }
    
  2. 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!
    
  3. Write a function named printSquares() with an int parameter named size that returns nothing (void).

    Add 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
    }
    
  4. Call your function inside the do-while loop of main() so that it will print out a square given the user input for the length of a side.
  5. 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!
    
  6. 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 hereClick to show answer 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.

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 values from a function call

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;
    

Exercise 8.3: Coding return (10m)

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, return to the main room.

Specifications

  1. Start Replit 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;
    }
    
  2. 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)
    
  3. Add a pair of curly braces for the function body: { }.
  4. Inside the function body, subtract the second parameter from the first and return the value.
  5. Compile and run your code. What do you see when you compile and run? (click here) Click to show answer
  6. 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;
    
  7. Compile and run your program and verify the output looks like:
    Enter two numbers to subtract: 3 1
    Difference=2
    
  8. 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 hereClick to show answer 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.

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

  • As we add more code to main(), it becomes too long to easily understand
  • A solution is to break up the long sequences of code into shorter sections using functions

    Function: a named block of statements that can receive input, perform an action, and optionally return a value

  • Functions allow us to organize code into short reusable pieces
  • Creating functions is like adding new commands to the programming language

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

  • As part of incremental development, programmers write function stubs

    Stub: a minimal set of code to act as a placeholder for a function

  • Function stubs are like an outline of a function but without the program statements
  • When a function must return a value, we return a "dummy" value--see below
  • Stubs allows us to design and code a high-level structure to a program without worrying about the details
  • The FIXME message lets us know the function is not finished

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

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. Choose one person to present your solution to the rest of the class if called upon. When the team has finished, return to the main room.

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.
  • Meaningful variable and function names.

Specifications

  1. Start Replit 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;
    }
    
  2. 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.
    
  3. Before main(), add the following function.
    double ComputeEnergyConsumed(double power, double hours) {
       return (power * hours) / 1000;
    }
    
  4. 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.

  5. 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 hereClick to show answer 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.

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

  • To use functions well, we must understand the flow of a program when calling functions
  • Every program starts executing in the main() function
  • When a program gets to a statement like the following, it stops executing in main() and jumps to our function:
    int total = add(num1, num2);
    
  • The program executes the statements in the function and then returns to the point in the code right after where it jumped
  • When the function returns, the returned value (conceptually) replaces the function call
  • After returning, the program completes processing the calling statement and then moves on to the next statement
  • In our example, the statement saves the returned value in the variable: total

Function Call Flow

Flow of control for a function call
  1. Every program starts executing at the start of the function main().
  2. When reaching a function call, arguments are copied to the parameters.
  3. Function code executes until reaching a return statement.
  4. Return statement returns a value to the function call.
  5. 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"

    Person sitting in yoga pose with a 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:
    1. Temporarily stops executing in the current function
    2. Jumps to the called function and executes the statements of that function
    3. Returns to the point in the code from which it jumped
    4. Continues with the next instruction
  • 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;
}

Exercise 8.5: Tracing flow (10m)

Be the computer

Be the computer

In this exercise we trace the flow of control of 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, return to the main room.

Specifications

  1. Create a text file named trace.txt.
  2. 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.

  3. Review the code trace with the other members of your team. 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, ...
  4. Save the trace.txt to submit to Canvas with the rest of the exercise files for the week.

When finished with your trace click hereClick to show answer to verify.

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

  • The area of code that a variable can operate within is known as it's scope

    Scope: the enclosing area within which a variable exists

  • Because of scope, we may use variables with the same name in different functions
  • To send information to a function we must use a parameter:
    int add(int a, int b)
    
  • When the function call is made, we send the arguments to the parameters:
    add(num1, num2)
    
  • The values of num1 and num2 are copied to the parameter variables a and b

Passing Arguments to Function Parameters

Passing arguments in a function call

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

  • Notice the constant variable PI in the above example:
    const double PI = 3.14159265;
    
  • C++ lets us define variables and constants with a global scope
  • Global variables and constants are declared outside of any function and can be accessed in any function
  • If local variables have the same name, then local variables take precedence over global variables
  • Because they have the same value everywhere, and cannot be changed, global constants are acceptable programming practice

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

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. Choose a team member to report the expected output. When the team has finished, return to the main room.

Specifications

  1. Create a text file named globalout.txt.
  2. 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.

  3. As a team, trace the code and decide on the output of the code without running it.
  4. Type the expected output into the gobalout.txt file.
  5. Save the globalout.txt file to submit to Canvas with the rest of the exercise files for the week.

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;
}

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, return to the main room.

Specifications

  1. Start Replit 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;
    }
    
  2. Compile and run the code to see the error produced.
  3. Add function declarations (function prototypes) to resolve the errors.
  4. After resolving the error, reverse the order of FunA() and FunB() and compile again.
  5. Add function declarations (function prototypes) to resolve the errors, if any.
  6. Move FunA() and FunB() below main() and compile again.
  7. Add function declarations (function prototypes) to resolve the errors, if any.
  8. 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 hereClick to show answer 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.

8.7: Unit testing

Testing is the process of checking whether a program behaves correctly. Unit test is testing the smallest parts of a program.

8.7.1: Reviewing unit testing

  • Testing a large program can be hard because bugs may appear anywhere in the program
  • In addition, multiple bugs may interact
  • Good practice is to test small parts of the program individually, before testing the entire program
  • Unit testing is the process of individually testing a small part or unit of a program, typically a function
  • To unit test we write code to call a function and check its return values or output
  • Each test performed is known as a test case
  • We often use if-statements to test the returned value
  • For example, for the function:
    double square(double number) {
        double result = number * number;
        return result;
    }
    
  • We may write a test case
    double correctResult = 64;
    double actualResult = square(8);
    if (fabs(correctResult - actualResult) < 0.001) {
       cout << "Function square(8) correctly returns " << actualResult << endl;
    } else {
       cout << "Function square(8) incorrectly returns: " << actualResult << endl;
    }
    
  • Another option is the assert statement as covered in the textbook

Exercise 8.7: Unit tests to evaluate your program (10m)

The exercise for this section is in Zybooks, section 8.12 Lab training: Unit tests to evaluate your program. Activate the exercise from Canvas for credit.

8.8: Random numbers

Random numbers are a series of numbers whose future values cannot be predicted.

8.8.1: Reviewing random numbers

  • Many computational problems need to use random numbers like:
    • Cryptography in many areas including generating passwords
    • Simulation of unpredictable real phenomena
    • Random numbers in games of chance like dice rolling
    • Random shuffling of the audio files in an audio player
  • The C++ library has a random number generator, rand(), that produces a series of psuedorandom numbers:
    • Range is 0 up to and including RAND_MAX
    • Returns a "random" int value
  • To make use of the rand() function we may need to include the library:
    #include <cstdlib>
    
  • The syntax for calling the function is:
    rand()
    
  • For example:
    int randNumber = rand(); // returns number between 0 and RAND_MAX
    

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

  1. A number whose value cannot be predicted ahead of time is known as a ________ number.
  2. The problem with this random number generator from xkcd is that ________.
    1. dice rolling is not a fair way to get random numbers
    2. it was not selected randomly
    3. you can predict the number ahead of time
    4. nothing is wrong
  3. The function rand() returns a number between ________ and including ________.

8.8.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
  • Thus a good strategy is to call srand(time(0)) at the start of main()

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

  1. The function that sets the starting location, or seed, for rand() is ________.
  2. To produce a new random number sequence every time a program starts use the code: ________.
  3. True or false: you must reseed the random number generator every time before calling rand().

Exercise 8.8: 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, return to the main room..

Specifications

  1. Start Replit and copy the following program into a text editor.
    #include <iostream>
    using namespace std;
    
    int main() {
        // Enter your code here
    
        return 0;
    }
    
  2. Compile and run the starter program to make sure you entered it correctly. No output is expected when run.
  3. 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>
    
  4. 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;
    
  5. 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.

  6. 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.

  7. 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
    
  8. 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));
    
  9. 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 hereClick to show answer 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.

Deliverables

For this week's exercises we are turning in these files:

Remember that when submitting multiple files to Canvas, you must submit all files in the same session. For instuction on submitting multiple files for an assignment see the Canvas guide on How do I upload a file as an assignment submission in Canvas? section: Submit Assignment.

Lab Introductions

Here are a few tips on how to get started on the labs.

Last Updated: October 23 2021 @22:19:56