Lab: Functions

Learning Objectives

Exercise 1: Detecting prime numbers with functions (10 points)

Implement a function that takes an integer value and returns true if the integer is a prime number and false otherwise. The function should have the following signature.

bool is_prime(int n)

Use an assert statement inside the function to check the precondition that n is greater than one.

Include the function in a console program that calls the is_prime function with a range of values that test several common cases as well as the boundary cases. Use an assert statement for each test case. For example, the following tests that the function returns false for the value 100.


You need to include the cassert header in your code in order to use the assert function.

#include <cassert>

Exercise 2: Listing prime numbers with functions (10 points)

In the previous lab, you wrote a console application that computes and displays all the prime numbers inclusively between 2 and a number entered by the user. Write a program that has the same inputs and outputs as this previous exercise, but this time use the is_prime function you developed in the previous problem to simplify your code. Specifically, replace the inner loop by a call to is_prime so that your new program uses a single loop inside the main function rather than a loop nested within another loop.

Exercise 3: Listing random colors with functions (10 points)

Re-organize the code in your solution to Listing random colors problem of the previous lab so that generation of a random color string is performed in a function. Use functions to remove any nested loops (loops within loops) that are in your code.

Exercise 4: Generate a web page (10 points)

Write a program that generates a web page that contains a list of 100 random RGB color values. The program should write something like the following into cout.

    <title>Assignment 1 Exercise 2</title>
        <li style="color: #324AF3">324AF3</li>
        <li style="color: #6A3125">6A3125</li>

         ... 98 additional list items here ...


Organize your code using functions.

The following shows how to save the output of your program to a file named colors.html. After doing this, open the file in a web browser to see the result.

./a.out > colors.html