100% satisfaction guarantee Immediately available after payment Both online and in PDF No strings attached 4.2 TrustPilot
logo-home
Exam (elaborations)

COS1512 Assignment 3 (QUALITY ANSWERS) 2024

Rating
-
Sold
-
Pages
38
Grade
A+
Uploaded on
23-06-2024
Written in
2023/2024

This document contains workings, explanations and solutions to the COS1512 Assignment 3 (QUALITY ANSWERS) 2024. For assistance call or us on 0.6.8..8.1.2..0.9.3.4...... Question 1 Consider the following structure used to keep record of a student’s scores: struct Student { string name; int quiz1; int quiz2; int midtermExam; int finalExam; } A student is assessed according to the following policies: 1. The two quizzes are each marked out of 10. 2. The midterm exam and the final exam are each marked out of 100 marks. 3. The final exam counts for 50% of the grade, the midterm counts for 25%, and the two quizzes together count for a total of 25%. (Do not forget to normalize the quiz scores. They should be converted to a percentage before they are averaged in.) Turn the student record into a class type rather than a structure type. The student record class should have member variables for all the input data. Make all member variables private. Include public member functions for each of the following: • a default constructor that sets the student ‘s name to a blank string, and all the scores to 0; • member functions to set each of the member variables to a value given as an argument to the function (i.e. mutators); • member functions to retrieve the data from each of the member variables (i.e. accessors); • and a function that calculates and returns the student’s weighted average numeric score for the entire course. Use this class in program which grades a student. The program should read in the student’s name and scores and output the student’s record as well as the student’s average numeric score for the entire course. Use the keyboard to supply input and display the output on the screen. Test your program with the following input: Student name: Johnny Applemac Quiz 1: 7 Quiz 2: 5 Midterm exam: 65 Final exam: 73 Downloaded by Corona Virus () lOMoARcPSD| COS1512/103/2024 3 Question 2 – a bit of theory and terminology (a) What is the purpose of the keywords public and private in the class declaration? (b) What is the difference between a class and an object? (c) What does it mean to “instantiate” an object? (d) What is the purpose of a constructor? (e) What is the difference between the default constructor and the overloaded constructor? (f) What is the purpose of a destructor? (g) What is the purpose of an accessor? (h) What is the purpose of a mutator? (i) What is the purpose of the scope resolution operator? (j) What is the difference between the scope resolution operator and the dot operator? (k) What is the difference between a member function and an ordinary function? (l) What is an abstract data type (ADT)? (m) How do we create an ADT? (n) What are the advantages of using ADTs? (o) What is separate compilation? (p) What are the advantages of separate compilation? (q) What is a derived class? (r) What is the purpose of inheritance? Downloaded by Corona Virus () lOMoARcPSD| COS1512/103/2024 4 Question 3 Consider the following class declaration: class PersonType { public: PersonType(); PersonType(string n, int id, string bd); private: string name; int ID; string birthday; }; Explain what is wrong with the following code fragment and write code to correct it: int main() { PersonType family[20], newBaby("Anny Dube", , "2 Sept"); //Assume family has been initialised for (int i = 0; i < 20; i++) if (day[5] == newBday) cout << [5] << " share a birthday with " <<newB; return 0; } Question 4 Consider the following class declaration: class Date{ public: //constructors Date(); Date(int day, int month, int year); //accessors int getDay() const; int getMonth() const; int getYear() const; //mutators void setDay(int day); void setMonth(int month); void setYear(int year); //operators to calculate next and previous days Date &operator++(); Downloaded by Corona Virus () lOMoARcPSD| COS1512/103/2024 5 Date &operator--(); bool operator<(const Date &d); private: //the current day month and year int theday; int themonth; int theyear; //return the length of current month, taking into //account leap years int monthLength(); }; Implement and test the Date class, taking the following guidelines into account: a) The default constructor should initialise the date to 14 September 1752. b) The overloaded constructor should initialise the date with the given day, month and year. c) The functions getDay(), getMonth() and getYear() should return the current day, month and year respectively. d) The functions setDay(), setMonth() and setYear() should change the current day, month or year to the given value. e) The operator ++ should advance the date by one, and return the new date. f) The operator -- should set the date back by one day, and return the new date. g) The operator < should calculate whether the receiving date object (left argument) precedes the parameter date (right argument). For example, Date(1,1,2002) < Date(1,3,2002). h) The private member function monthLength() should return the length of the current month, taking into account leap years. A year is a leap year if it is either (i) divisible by 4, but not by 100, or (ii) divisible by 400. In a leap year, February has 29 days, otherwise it has 28 days. i) Also overload the insertion operator << to output a date to the screen. For example, the date in (a) above should be written as: 14 September 1752. Test the Date class in a C++ program that will do the following: • Declare a new Date object called d1. • Display the day, month and year of d1 on the screen. • Change the date to 28 February 2000. • Advance this date by one and display the new date on the screen. • Now change the date to 1 January 2002. • Set this date back by one and display the new date on the screen. • Finally change the date to 31 December 2002. • Advance this date by one and display the new date on the screen. • Declare a second date object d2(1,1,2003). • Determine if d1 is earlier than d2 and write the result on the screen. • Operators ++, -- and < are declared as member functions in the class declaration above. Implement these operators as friend functions of class Date also. Run your program twice (each time with a different version of the overloaded operator ++, -- and <; comment the other versions out during each run). Downloaded by Corona Virus () lOMoARcPSD| COS1512/103/2024 6 Enrichment exercise: Turn the Date class into an ADT, so that separate files are used for the interface and implementation. Use separate compilation to compile the implementation separate from the application program that tests the ADT. PLEASE NOTE: The enrichment exercises do not form part of the assignment. It is for practice only. Question 5 Define a class PhoneCall as an ADT that uses separate files for the interface and the implementation. This class represents a phone call and has three member variables: • number, a string that holds the phone number (consisting of 10 digits) to which a call is placed • length, an int representing the length of the call in minutes • rate, a float representing the rate charged per minute. In addition, the class should contain a default constructor that initializes number to an empty string, length to 0 and rate to 0. It should also contain an overloaded constructor that accepts a new phone number and sets length and rate both to 0, as well as a destructor that does not perform any action. Include accessor functions that returns the values stored in each of an object of class PhoneCall’s member variables respectively. Class PhoneCall also contains a member function calcCharge() to determine the amount charged for the phone call. Use the following prototype: float calcCharge(); Overload the equality operator== as a friend function to compare two phone calls. Use the following prototype: bool operator==(const PhoneCall & call1, const PhoneCall & call2) This function returns true if both call1 and call2 have been placed to the same number and false otherwise. Overload the stream extraction operator >> (implemented as a friend function) so that it can be used to input values of type PhoneCall, and the stream insertion << (implemented as a friend function) so that it can be used to output values of type PhoneCall. Demonstrate the class in an application program (main()) that is used to determine the total amount spend on phone calls to a specific phone number in one month. Allow the user to enter the phone number for which the total amount spent should be determined. Use the overloaded constructor to initialise the PhoneCall object theCall to the number the user specified. The PhoneCall objects representing the calls made during one month is stored in a file MyC. Use a while loop to read the phone calls from MyC, use the overloaded equality operator== to compare the phone numbers read from MyC one by one with theCall, and determine the total amount spend on phone calls to theCall, as well as the number of calls made to this number. Also determine the longest call made to theCall and display this call together with the total amount spent on calls to theCall, and Downloaded by Corona Virus () lOMoARcPSD| COS1512/103/2024 7 the number of calls to theCall. Test your program with the following data: Phone calls in file MyC: .50 .15 .75 15 3.15 .75 .50 .50 .15 .15 Phone number to test: Question 6 Overload the stream extraction operator >> for the class Student in Question 1 to read values for each member variable from a file. Also overload the stream insertion operator << to print the record for a student (name, two quiz scores, midterm score and final exam score) as well as the weighted average for the student either on the screen or to a file. Use separate compilation and write a program that uses the overloaded extraction operator >> to read records for students from a file named S into an array. Assume that the file will never contain data for more than 20 students. Use the array to determine the weighted average for each student, as well as the average for all of the students (i.e. the class average). Display the output on the screen. Use the following data: Peter Pan 5 3 45 51 Wendy Hill 7 5 63 58 Alice Mokgaba 8 6 51 67 Precious Petersen 5 7 49 46 Thumi Tebogo 4 7 69 65 Enrichment exercise: Adapt the application program to use a vector instead of an array. It should not be necessary to change the class interface or implementation file in any way. Question 7 Define a class Student with member variables for a student’s name, student number, address and degree. All of these member variables are strings. Add appropriate constructors and accessors for class Student and include the following member functions: • a member function display_info()that overloads the stream insertion operator << to display the values of all the member variables of a student. • a member function calcFee() to calculate the initial registration fee for a student. For undergraduate students the initial registration fee is R500 and for postgraduate Downloaded by Corona Virus () lOMoARcPSD| COS1512/103/2024 8 students the initial registration fee is R600. All undergraduate student degrees begin with a “B” which will allow you to determine whether a student is an undergraduate or postgraduate student. (a) Implement class Student. (b) Test class Student in a driver program that does the following: • instantiates an object of class Student, with the following details:name: Mary Mbeli student number: address: Po Box 16, Pretoria, 0818 degree: BSc • use the accessor functions to display the specifications of the instantiated object on the console • display the specifications of the instantiated object on the console with the member function display_info(). • calculate and display the fee for the student. (c) Derive and implement a class PostgradStd from class Student. This class has an additional member variable, dissertation (the title of the Masters of doctorate the student is doing). Class PostgradStd also has an overloaded constructor and an accessor member to return the member variable dissertation. The class PostgradStd should override function display_info() in order to display the values of all the member variables of PostgradStd. The class PostgradStd should also override function calcFee() to determine the additional fee for a postgraduate student which is R12000. Implement the overloaded constructor for the class PostgradStd by invoking the base class constructor. (d) Test class PostgradStd in a driver program that does the following: • instantiates an object of class PostgradStd, with the following details: name: Mary Mbeli student number: address: Po Box 16, Pretoria, 0818 degree: PhD dissertation: How to get a PhD • use the accessor functions to display the specifications of the instantiated object on the console • display the specifications of the instantiated object on the console with the member function display_info(). calculate and display the outstanding fee for the student.

Show more Read less
Institution
Course











Whoops! We can’t load your doc right now. Try again or contact support.

Connected book

Written for

Institution
Course

Document information

Uploaded on
June 23, 2024
Number of pages
38
Written in
2023/2024
Type
Exam (elaborations)
Contains
Questions & answers

Subjects

Content preview

COS1512
Assignment 3 2024
Unique #:160814
Due Date: 23 August 2024



This document includes:

• Helpful answers and guidelines
• Detailed explanations and/ or calculations
• References



Connect with the tutor on

+27 68 812 0934

,4. Solution to Assignment
Question 1 max of 5 marks

Discussion:
For this question, you had to convert the struct Student into a class. There is essentially only a slight
difference between a struct and a class. A class is the same as a struct (i.e. a struct may also
contain both member variables and member functions just like a class, even though the examples in
Savitch do not show that) except that, by default, all members are inaccessible to the general user of the
class. This means that all members of a struct are by default public, and all members of a class are
by default private. Therefore, we have to specify that the member functions are public. (As an
exercise, omit the public keyword from the class and recompile it.) While there are situations where a
struct is more suitable, as a rule, you should use classes rather than structs. In general, it is preferable
to use classes, as classes offer better protection.

An object encapsulates or combines data and operations on that data into a single unit. In C++, the
mechanism that allows you to combine data and the operations on that data in a single unit is called a
class.

As name, quiz1, quiz2, midtermExam and finalExam are private member variables (see page
549 of Savitch 6th edition/ page 581 of Savitch 7th edition/ pages 573-582 of Savitch, 8th edition/pages
589-595 of Savitch, 9th edition) of class Student, they cannot be accessed directly in the main()
function. As a result, public member functions getQuiz1(), getQuiz2(), getMidtermExam(),
getFinalExam() and Term() are used to access these member variables in order to determine their
values. These functions are known as accessor functions, while setName(), setQuiz1(), setQuiz2(),
setMidtermExam()and setFinalExam()are mutator functions. (Study pages 553-554 of Savitch, 6th
edition/ pages 585-586 of Savitch 7th edition/ pages 581-582 of Savitch, 8th edition/ pages 597-598 of
Savitch, 9th edition).

Mutator functions are used to change or modify member variables of an object. The parameter of the
mutator function typically indicates the value according to which the member variable should be changed.
For example, the mutator function setQuiz1()below modifies member variable quiz1 to q1:
void Student::setQuiz1(int q1)
{
quiz1 = q1;
}

Note the prototypes for member functions:
string getName()const;
int getQuiz1()const;
int getQuiz2()const;
int getMidtermExam()const;
int getFinalExam()const;

These member function are accessors - hence the const keyword at the end of the function definition.
Note that a member function that does not have the const keyword at the end of it could mutate (change
or modify) the state of the object. Although member function calcAverage() is not an accessor, it should
not modify the object, and therefore the prototype for member function calcAverage() also has the
const keyword at the end of the function definition:
int calcAverage()const;

,Program listing:
#include <iostream>
#include <string>
using namespace std;

//Class declare
class Student
{
public:
Student();
void setName(string n);
void setQuiz1(int q1);
void setQuiz2(int q2);
void setMidtermExam(int m);
void setFinalExam(int f);
string getName()const;
int getQuiz1()const;
int getQuiz2()const;
int getMidtermExam()const;
int getFinalExam()const;
int calcAverage()const;
private:
string name;
int quiz1;
int quiz2;
int midtermExam;
int finalExam;
};

//Implementation of member functions for class Student
Student::Student()
{
name = " ";
quiz1 = 0;
quiz2 = 0;
midtermExam = 0;
finalExam = 0;
}

void Student::setName(string n)
{
name = n;
}

void Student::setQuiz1(int q1)
{
quiz1 = q1;
}

void Student::setQuiz2(int q2)
{
quiz2 = q2;
}

void Student::setMidtermExam(int m)
{
midtermExam = m;
}

, void Student::setFinalExam(int f)
{
finalExam = f;
}
string Student::getName()const
{
return name;
}

int Student::getQuiz1()const
{
return quiz1;
}

int Student::getQuiz2()const
{
return quiz2;
}

int Student::getMidtermExam()const
{
return midtermExam;
}

int Student::getFinalExam()const
{
return finalExam;
}

int Student::calcAverage()const
{
return int((quiz1 * 10 + quiz2 * 10)/2 * 0.25 + midtermExam * 0.25
+ finalExam * 0.5);
}
//Main function of application
int main()
{
Student aStudent;
string n;
int q1,q2,m,f;

// Obtain student detail
cout << "Please enter student's name: ";
getline(cin, n);
aStudent.setName(n);
cout << "Enter mark for quiz 1: ";
cin >> q1;
aStudent.setQuiz1(q1);
cout << "Enter mark for quiz 2: ";
cin >> q2;
aStudent.setQuiz2(q2);
cout << "Enter mark for midterm exam: ";
cin >> m;
aStudent.setMidtermExam(m);
cout << "Enter mark for final exam: ";
cin >> f;
aStudent.setFinalExam(f);

Get to know the seller

Seller avatar
Reputation scores are based on the amount of documents a seller has sold for a fee and the reviews they have received for those documents. There are three levels: Bronze, Silver and Gold. The better the reputation, the more your can rely on the quality of the sellers work.
StudyShack Cornerstone College, Pretoria, Gauteng
Follow You need to be logged in order to follow users or courses
Sold
30694
Member since
9 year
Number of followers
13937
Documents
1800
Last sold
1 month ago
Study Guides for Unisa Students

4.1

1778 reviews

5
970
4
335
3
264
2
80
1
129

Recently viewed by you

Why students choose Stuvia

Created by fellow students, verified by reviews

Quality you can trust: written by students who passed their tests and reviewed by others who've used these notes.

Didn't get what you expected? Choose another document

No worries! You can instantly pick a different document that better fits what you're looking for.

Pay as you like, start learning right away

No subscription, no commitments. Pay the way you're used to via credit card and download your PDF document instantly.

Student with book image

“Bought, downloaded, and aced it. It really can be that simple.”

Alisha Student

Frequently asked questions