CS 200: Concepts of Programming with C++, Summer 2022
🔙 BACK TO UNIT PAGE | CANVAS TURN IN
Exercises are meant to be solo effort, please try to complete it on your own. You can ask the instructor or a tutor questions if you get really stuck, but all the information you need to complete the assignment is in here, or in the related reading/lectures.
If you get stuck, please post questions in the Unit 7 'Help!' discussion board.
FIRST, from your "My Repls" page on Repl.it create a New folder for this weeks' assignments name it Unit07. Within this folder you will create separate Repl projects for each program. When you turn in the assignments, you will copy the URL to your folder as the submission.
First, make sure all your programs are inside your Unit07 folder. If they're not you can click on the three dots on the right side of the program name and click "Move".
PLEASE GIVE YOUR PROGRAMS THE FOLLOWING NAMES:
Clean code also means the ability to find the code itself, so if your project is unkempt and hard to navigate you will lose points.
To submit your work, navigate to the folder for your exercises on replit. Copy the URL to that directory (e.g., https://replit.com/@rsingh13?path=folder/Unit07) and paste it in here in Canvas.
Once you've turned in the assignment, make sure to also post your program in the code review assignment, [CS200.U07.PR] 🔎 Classes and Inheritance - Peer review
Quick jump: Program 1: RPG Dice | Program 2: Quiz v1 | Program 3: Quiz v2 | Program 4: Courses | Program 5: Basic inheritance
⭐
When playing tabletop games, players usually have several sets of
dice with different amount of sides.
How many sides should the die have? 20 How many times do you want to roll the die? 6 Roll #1: 10 Roll #2: 7 Roll #3: 1 Roll #4: 3 Roll #5: 6 Roll #6: 15
You will need a main.cpp file for main() and a Die.h file for the class declaration and a Die.cpp for the function definitions.
Since we are going to use random numbers, make sure to include the following in your Die.cpp file:
#include <cstdlib>
And in your main.cpp include:
#include <cstdlib>
#include <ctime>
srand( time( NULL ) );
We are going to create a simple class with the following requirements. Remember that class and function declarations go in the Die.h file and function definitions go in the Die.cpp file.
UML Notes:
-
are private
+
are public
NAME : DATATYPE
, so in code it would be DATATYPE NAME;
NAME( PARAM : TYPE, PARAM : TYPE ) : RETURNTYPE
, so in code it would be RETURNTYPE NAME( TYPE PARAM, TYPE PARAM )
Die |
---|
- m_sides : int |
+ SetSides( sides : int ) : void |
+ RollDie() : int |
Function Name
void Die::SetSides( int sides );Inputs
sides, an intReturns
void
Within this function, set the value of m_sides
to the value passed in as the sides
parameter.
Function Name
int Die::RollDie()Inputs
NoneReturns
int
Within this function we're going to call the random number function, using 1 as the minimum and sides
as the maximum. To get a random number in this range, we have to use this:
return rand() % ( max - min + 1 ) + min;
(Yes, it's ugly, but this is why writing a nice "Get Random" function would be useful ;)
Your min will be 1, and the max will be whatever the amount of sides is.
Remember that your class declaration and function declarations go in the Die.h file and the function definitions go in the Die.cpp file.
Once you're finished with these steps, Die.h should look like this:
// DON'T FORGET THE FILE GUARDS!
#ifndef _DIE_H
#define _DIE_H
class Die
{
public:
int Roll();
void SetSides( int sides );
private:
int m_sides;
}; // DON'T FORGET THE ; AT THE END!
#endif
And Die.cpp should look like this:
#include "Die.h"
#include <cstdlib>
int Die::Roll()
{
int min = 1;
int max = m_sides;
return rand() % ( max - min + 1 ) + min;
}
void Die::SetSides( int sides )
{
m_sides = sides;
}
Beneath all of that we will write the actual program. Do the following steps:
srand( time( NULL ) );
int sides = 0;
cout << "How many sides should the die have? ";
cin >> sides;
rolls
:
int rolls = 0;
cout << "How many times do you want to roll the die? ";
cin >> rolls;
myDie
and initialize it as a Die class object:
Die myDie;
SetSides
function:
myDie.SetSides( sides );
rolls
times (for ( int i = 1; i <= rolls; i++ )
).
Within the for loop, do the following:
Roll()
function, storing the result in a new variable called result
.
int result = myDie.Roll();
cout << "Roll #" << i << ": " << result << endl;
Once all of the code is done your program should look like this:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
#include "Die.h"
int main()
{
srand( time( NULL ) );
int sides = 0;
cout << "How many sides should the die have? ";
cin >> sides;
int rolls = 0;
cout << "How many times do you want to roll the die? ";
cin >> rolls;
Die myDie;
myDie.SetSides( sides );
for ( int i = 1; i <= rolls; i++ )
{
int result = myDie.Roll();
cout << "Roll #" << i << ": " << result << endl;
}
return 0;
}
And the program output will look like this:
How many sides should the die have? 20 How many times do you want to roll the die? 6 Roll #1: 10 Roll #2: 7 Roll #3: 1 Roll #4: 3 Roll #5: 6 Roll #6: 15
⭐⭐
For this program we will create a Question class that will ask the user a question, get their guess, and check if their result was correct or not.
What command do you use to display information in Python? Your guess: print CORRECT!
Create a project and create the following files: main.cpp, Question.h, and Question.cpp.
Function Name
void Question::Setup( string question, string answer );Inputs
question, a stringReturns
voidThis function takes two inputs, question and answer. Assign the corresponding private member variable to each of these items.
Question |
---|
- m_question : string |
- m_answer : string |
+ Setup( question : string, answer : string ) : void |
+ AskQuestion() : bool |
Function Name
bool Question::AskQuestion();Inputs
noneReturns
boolWithin the function, do the following:
Once the class is done, Question.h should look like this:
#ifndef _QUESTION_H
#define _QUESTION_H
#include <string>
using namespace std;
class Question
{
public:
bool AskQuestion();
void Setup( string question, string answer );
private:
string m_question;
string m_answer;
};
#endif
Once the class is done, Question.cpp should look like this:
#include "Question.h"
#include <iostream>
using namespace std;
bool Question::AskQuestion()
{
cout << m_question << endl << endl;
string guess;
cout << "Your guess: ";
getline( cin, guess );
cout << endl;
if ( guess == m_answer )
{
cout << "CORRECT!" << endl;
return true;
}
else
{
cout << "INCORRECT!" << endl;
return false;
}
}
void Question::Setup( string question, string answer )
{
m_question = question;
m_answer = answer;
}
Within main(), do the following:
Even though the function returns true and false, we won't check on that result
until v2 of the Quizzer, so for now it is fine that it just prints CORRECT! or INCORRECT!
Test out the program and make sure it looks like the example output.
Don't forget that in main.cpp you need to include the Question.h file! Never include .cpp files!
⭐⭐⭐
For v2 of the Quiz program, we will write a class for a Quiz, which contains a list of Questions within it.
QUESTION 1 What command do you use to display information in Python? Your guess: print CORRECT! QUESTION 2 What command do you use to get information from the keyboard in Python? Your guess: input CORRECT! QUESTION 3 What is the add operator in Python? Your guess: * INCORRECT! QUESTION 4 How do you declare a variable named 'num' and assign it a value of 2? Your guess: num = 2 CORRECT! RESULTS Score: 0.75%
Create a fork of the Quiz v1 program and rename this project Quiz v2. You will need to add a Quiz.h file and a Quiz.cpp file.
If you make a new project instead, make sure to copy over your Question.h and Question.cpp files.
Function Name
CreateQuestionInputs
index, an intReturns
void
This function is responsible for setting up questions in the
m_questionList
array at the index passed in.
Call the Question's Setup
function.
Quiz |
---|
- m_questionList : Question size [4] |
+ CreateQuestion( index : int, question : string, answer : string ) : void |
+ Run() : void |
Function Name
Run()Inputs
noneReturns
voidWithin the function, do the following:
totalRight
and initialize it to 0.m_questionList
. Within the for loop, do the following:
i+1
to make it more human-friendly.)m_questionList[i]
.
Call the current question's AskQuestion()
function,
storing its result in a new boolean variable called result
.
result
is true
, then add 1 to the totalRight
variable.totalRight
by
the length of the array (use 4.0
, because if you divide two integers it will not have the remainder),
then multiplying by 100.The Quiz.h file will look like this:
#ifndef _QUIZ_H
#define _QUIZ_H
#include "Question.h"
class Quiz
{
public:
void CreateQuestion( int index, string question, string answer );
void Run();
private:
Question m_questionList[4];
};
#endif
The Quiz.cpp file will look like this:
#include "Quiz.h"
#include <iostream>
using namespace std;
void Quiz::CreateQuestion( int index, string question, string answer )
{
m_questionList[index].Setup( question, answer );
}
void Quiz::Run()
{
int totalRight = 0;
for ( int i = 0; i < 4; i++ )
{
cout << "QUESTION " << i << endl;
bool result = m_questionList[i].AskQuestion();
if ( result == true )
{
totalRight++;
}
cout << endl;
}
float scorePercent = totalRight / 4.0;
cout << endl << "RESULTS" << endl;
cout << "Score: " << scorePercent << "%" << endl;
}
Remove the old Question code from v1 of the quiz in main.cpp. This time, we're going to create a Quiz variable and use it to create all of our questions.
Create a Quiz object named quiz
.
Call the CreateQuestion
function several times to set up questions:
quiz.CreateQuestion( 0, "What command do you use to display information in Python?", "print" );
quiz.CreateQuestion( 1, "What command do you use to get information from the keyboard in Python?", "input" );
quiz.CreateQuestion( 2, "What is the add operator in Python?", "+" );
quiz.CreateQuestion( 3, "How do you declare a variable named 'num' and assign it a value of 2?", "num = 2" );
Once all the setup is done, call the Quiz's Run
function to run the quiz when the program begins.
The program output should look like the example above.
⭐⭐⭐⭐
For this program you will be creating a class to store a Person's info and a Course's info. Similar to the Quiz, the Course will have a list of students.
COURSE NAME: CS134 COURSE CODE: Programming Fundamentals INSTRUCTOR: Rachel Singh (5944) STUDENTS: 0. Ellene Largen (7184) 1. Sol Groucutt (4803) 2. Anton Caghan (6229) 3. Mei Drohane (4577)
The person class will be used to store information on students and the teacher of a course.
Function name
SetupInputs
id, an intReturns
voidTake the parameters and assign their values to the corresponding member variables.
Function name
DisplayInputs
NoneReturns
voidDisplay the person's name and id to the screen.
Person |
---|
- m_id : int |
- m_name : string |
+ Setup( id : int, name : string ) : void |
+ Display() : void |
The Course class contains basic information about a course, including a list of students and the teacher.
Function name
Course constructorInputs
NoneReturns
NoneInitialize the m_studentCount
to 0 here.
Function name
SetupInputs
name, stringReturns
voidThis function takes the input parameters and assigns them to the corresponding private member variables.
Course |
---|
- m_name : string |
- m_code : string |
- m_teacher : Person |
- m_students[20] : Person |
- m_studentCount : int |
+ Setup( name : string, code : string ) : void |
+ AssignTeacher( id : int, name : string ) : void |
+ AddStudent( id : int, name : string ) : void |
+ DisplayCourseInfo(): void |
Function name
AssignTeacherInputs
id, an intReturns
voidGiven the input parameters id
and name
, call the m_teacher
's set up function to set up the teacher's info.
Function name
AddStudentInputs
id, an intReturns
voidAdd a new student to the m_students
array and increment the m_studentCount
afterwards.
Function name
DisplayCourseInfoInputs
NoneReturns
voidDisplay the course name and code. Next call the teacher's Display function. Finally, create a for loop to iterate over the student array and call each student's Display function.
Go to the https://mockaroo.com/ website to generate example IDs and names to fill out here. (Set the ID field to a "number" type, and the name field to "Full Name").
cs134
, initialized as a Course object.AssignTeacher
function, passing in a name and an id.AddStudent
function for at least four students, adding in names and ids generated with Mockaroo.DisplayCourseInfo
function to display the course information.The output will look like the example above.
⭐⭐
For this execise we'll step through a very simple example of using inheritance.
RECTANGLES Enter width: 4 Enter height: 3 The rectangle area is 12 CIRCLES Enter radius: 5 The circle radius is 78.5
Create a program that contains the files main.cpp, Shapes.h, and Shapes.cpp.
The Shape class will be the parent class of our other shapes. We're defining a CalculateArea function here, though it won't really do anything handy until we override it in the child classes.
The class declaration will look like this:
class Shape
{
public:
float CalculateArea();
};
And the function implementation will look like this:
float Shape::CalculateArea()
{
return 0;
}
Shape |
---|
+ CalculateArea() : float |
The Rectangle class inherits from the Shape class and will override the CalculateArea function. Additionally, a rectangle requires width and height information, as well as a function to interface with that data to set it up.
The class declaration will look like this:
class Rectangle : public Shape
{
public:
void Setup( float width, float height );
float CalculateArea();
private:
float m_width;
float m_height;
};
And the function definitions will look like this:
void Rectangle::Setup( float width, float height )
{
m_width = width;
m_height = height;
}
float Rectangle::CalculateArea()
{
return m_width * m_height;
}
Rectangle, inherits from Shape |
---|
- m_width : float |
- m_height : float |
+ Setup( width : float, height : float ) : void |
+ CalculateArea() : float |
The Circle class inherits from the Shape class and will override the CalculateArea function. Additionally, a circle requires radius information, as well as a function to interface with that data to set it up.
The class declaration will look like this:
class Circle : public Shape
{
public:
void Setup( float radius );
float CalculateArea();
private:
float m_radius;
};
And the function definitions will look like this:
void Circle::Setup( float radius )
{
m_radius = radius;
}
float Circle::CalculateArea()
{
return 3.14 * m_radius * m_radius;
}
Circle |
---|
- m_radius : float |
+ Setup( radius : float ) : void |
+ CalculateArea() : float |
We're not getting too deep into inheritance here, but if you take CS235 you will learn a lot more about ways inheritance can be used in an object oriented design.
Implement the following steps in main():
Once run, the output should look like this:
RECTANGLES Enter width: 4 Enter height: 3 The rectangle area is 12 CIRCLES Enter radius: 5 The circle radius is 78.5