0% found this document useful (0 votes)
8 views20 pages

Assignment 3 Solutions

Uploaded by

j.prokopes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views20 pages

Assignment 3 Solutions

Uploaded by

j.prokopes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

COS1511/501/0/2022

Tutorial letter 105/0/2022

Introduction to Programming I
COS1511

Year:2022

School of Computing

This tutorial letter contains the solutions for assignment 3


COS1511/105/2022

Dear Student

Your programs DO NOT HAVE TO BE IDENTICAL TO OURS, as long as you have followed the guidelines given in the
questions, and got the same output for the given input data. You should have used good programming techniques.

In the Study Guide we introduced certain conventions, amongst others

 that names of variables and the names of functions should start with lowercase characters and further
words in the names with uppercase characters,
 that the names of void functions should be verbs (or contain a verb) and
 that the names of value-returning functions should be nouns or adjectives.

Also
 use constants where needed
 avoid the use of global variables
 the correct indenting is extremely important
 remember to include comments
Below the mark allocation.

Question 1 20
Question 2 40
Question 3 10

To send an e-mail, please use the Course Contact on myUnisa.


Best wishes.

2
COS1511/105/2022

Question 1 20

BMI or Body Mass Index is a method of estimating a person's body fat levels based on a person's
weight and height measurement. The BMI is calculated by dividing the person’s body mass/weight (in
kilograms) by the square of the body height (in metres). The result is universally expressed in units of
kg/m2.
BMI formula: BMI = weight /(height)2

BMI Weight status


Below 18.5 Underweight
18.5-24.9 Healthy
25.0-29.9 Overweight
30.0 and above Obese

Write a program that calculates a person’s BMI and displays the weight status according to the BMI value,
indicating whether the person is underweight, healthy, overweight or obese. The BMI weight statuses
and related values are listed in the above table.

The program should have the following functions:


1.1. getData that prompts and returns their weight and height; (5)
1.2. calcBMI to calculate the BMI ; (5)
1.3. displayFitnessResults to display the BMI and relevant weight status message; (5)
1.4. main function (5)

3
COS1511/105/2022

Answer:

#include<iostream>

using namespace std;

void getData (double &getWeight, double &getHeight)


{
cout << "Enter your weight (in kilograms): ";
cin >> getWeight;
cout << "\nEnter your height (in Metres): ";
cin >> getHeight;
}

double calcBMI(double cWeight, double cHeight)


{
double bmi=0.0;

bmi = cWeight / (cHeight * cHeight);


return bmi;
}

void displayFitnessResults(double dBMI)


{
if(dBMI < 18.5)
cout << "Your BMI is "<< dBMI <<" You are underweight!! Eat More!! \n\n";

else if(dBMI >= 18.5 && dBMI <= 25)


cout << "Your BMI is "<< dBMI <<" You are in optimal shape!! Good Work! \n\n";

else if(dBMI >= 25 && dBMI <= 30)


cout <<"Youe BMI is "<< dBMI << " You are overweight!! Eat Less!! \n\n";

else if(dBMI >30)


cout <<"Youe BMI is "<< dBMI << " You are Obese!! Seek medical assistance for
dietary purposes!! \n\n";
}

//______________MAIN _FUNCTION______________

int main()
{
double weight, height, BMI;

cout << "BMI: Body Mass Index \n";


getData(weight, height);

BMI= calcBMI(weight, height);

displayFitnessResults(BMI);
4
COS1511/105/2022

return 0;
}

5
COS1511/105/2022

Question 2 40

Suppose we want to compile a student academic report for a high school learner in grade 12 (matric).
A matric learner is enrolled for 6 study units (subjects), namely: English, Mathematics, Life Orientation,
History, Computer literacy, Geography. The learner has to pass at least four subjects, including English,
to complete grade 12. The subject pass mark is 50%.

Write a program that prompts the learner to key in their marks for each subject. The program should
include the following functions:

a. A function studentDetails, that prompts the learner to key in their personal details
nameSurname, and schoolName. (3)

b. A function getMarks, that prompts the learner to key in a mark for each of the six subjects, and
validate the marks. Do not accept marks lower than 0 or higher than 100. (3)

c. A function calcAverageYearMark, to calculate and display the average of the 6 Subjects.


This function should be called just once by main, and should be passed the 6 Subject marks. (6)

d. A function minMax, to find and return the lowest and the highest of the 6 subject marks
passed to it as the subject with the lowest mark; (6)

e. A function passOrFail, to determine whether the student has passed or failed grade 12. (9)

f. A function awardDistinction to determine which of the subjects have received


distinctions. A subject receives a distinction if the mark is 75% and above. Also a student has
passed with distinction if the average mark is 75% and above. (3)

g. A function codeSymbol, to convert each mark to a symbol (A, B, C, D, E, F) and a code


(7,6,5,4,3,2,1). The symbol and code should be printed next to the mark in the student report.
The same should be calculated and displayed for the average mark. (6)

h. A function to Display the student report. (4)

Use the table below to determine the student symbol and code attained.
CODE SYMBOL MARK
7 A 80 - 100%
6 B 70 - 79%
5 C 60 - 69%
4 D 50 - 59%
3 E 40 - 49%
2 F 30 - 39%
1 FF 0 - 29%
6
COS1511/105/2022

Execute your program using the following data:

John Africa Mary Smith Thuli Booi


English 50% 48% 82%
Mathematics 76% 80% 66%
Life Orientation 40% 75% 62%
History 62% 70% 76%
Computer literacy 56% 86% 86%
Art 38% 72% 78%

You have to submit the program and output.

Sample run:
Please key in your name:
John Africa
Please key in the name of your school:
Kings College
Key in your mark for English:
50
Key in your mark for Mathematics:
76
Key in your mark for Life Orientation:
40
Key in your mark for History:
62
Key in your mark for Computer literacy:
56
Key in your mark for Geography/Art:
38
***************************************************
STUDENT ACADEMIC RECORD
This program inputs the learner marks of matric level
subjects and prints the student final report.
***************************************************
Name: John Africa School: Kings College

Subject Mark Symbol Code


English 50% D 4
Mathematics 76% B 6
Life Orientation 40% E 3
History 62% C 5
Computer literacy 56% D 4
Geography/Art 38% F 2

Average Year Mark: 53.67 with Symbol D and code 4

7
COS1511/105/2022

Outcome: Passed

The highest mark was 76%


The lowest mark was 38%
***************************************************

Answer:

#include<iostream>

using namespace std;

//a. A function studentDetails, that prompts the learner to key in their personal details
name, Surname, and schoolName. (3)

void studentDetails (string &name,string &surname, string &schoolName)


{
cout << "Enter the learner's first name : "<<endl;
cin >> name;
cout << "Enter your Last Name :"<<endl;
cin >> surname;
cout << "Enter your School Name :"<<endl;
cin >> schoolName;
return;
}

//b. A function getMarks, that prompts the learner to key in a mark for each of the six
subjects, and validate the marks. Do not accept marks lower than 0 or higher than 100. (3)

void getMarks(float &getEng, float &getMaths, float &getLifeOr, float &getHistory, float
&compLit, float &getGeo)
{
cout << "Enter your mark for English : "<<endl;
cin >>getEng;
while ( (getEng <0) || (getEng >100) )
{
cout << "invalid mark! Please Enter a mark for English between 0 and 100 : "<<endl;
cin >>getEng;
}

cout << "Enter your mark for Mathematics : "<<endl;


cin >>getMaths;
while ( (getMaths <0) || (getMaths >100) )
{
cout << "invalid mark! Please Enter a mark for English between 0 and 100 : "<<endl;
cin >>getMaths;
}

cout << "Enter your mark for Life Orientation : "<<endl;


cin >>getLifeOr;
while ( (getLifeOr <0) || (getLifeOr >100) )
{
cout << " invalid mark! Please Enter a mark for Life Orientation, between 0 and 100
: "<<endl;
cin >>getLifeOr;

8
COS1511/105/2022

cout << "Enter your mark for History : "<<endl;


cin >>getHistory;
while ( (getHistory <0) || (getHistory >100) )
{
cout << " invalid mark! Please Enter a mark for History, between 0 and 100: "<<endl;
cin >> getHistory;

cout << "Enter your mark for computer literacy : "<<endl;


cin >>compLit;
while ( (compLit <0) || (compLit >100) )
{
cout << " invalid mark! Please Enter a mark for Computer Literacy, between 0 and
100: "<<endl;
cin >> compLit;

cout << "Enter your mark for Geography : "<<endl;


cin >>getGeo;

while ( (getGeo <0) || (getGeo >100) )


{
cout << " invalid mark! Please Enter a mark for Geography, between 0 and 100:
"<<endl;
cin >> getGeo;

//c. A function averageYearMark, to calculate the average of the 6 Subjects. This function
should be called just once by main, and should be passed the 6 Subject marks. (6)

float calcAverageYearMark(float cEng, float cMaths, float cLifeOr, float cHistory, float
compL, float geo)
{
float total, average =0.0;

// number of subjects
int count =6;

// add subject marks to get the combined total


total = cEng + cMaths + cLifeOr + cHistory + compL + geo;

/* calculate the average as the combined total for all the subjects divided by the number
of subjects*/
average = total/count;

// return the value to Main


return average;
}

//d. A function minMax, to find and return the lowest and highest of the 6 subject marks passed
to it. (6)

void minMax(float cEng, float cMaths, float cLifeOr, float cHistory, float compL, float geo,
double &cMini, double &cMaxi)
{

9
COS1511/105/2022

double mini, maxi;


int size=6;

double calcArr[size];

calcArr[0]=cEng;
calcArr[1]=cMaths;
calcArr[2]=cLifeOr;
calcArr[3]=cHistory;
calcArr[4]=compL;
calcArr[5]=geo;

mini= calcArr[0];

maxi = calcArr[0];

for(int i = 1; i < size; i++)


{
if(calcArr[i] < mini)

mini = calcArr[i];

if(calcArr[i] > maxi)

maxi = calcArr[i];
}
cMini = mini;

cMaxi = maxi;
return;
}

//e. A function passFail, to determine whether the student has passed or failed grade 12.
The subject pass mark is 50%. Remember that a learner has to pass at least four subjects,
including English, to pass grade 12.

bool passOrFail (float eng, float maths, float lifeOr,float history,


float compLit, float geo)
{ bool passFail = false;
int passCount = 0;

if( eng < 50)


{
passFail= false;
}
else //check if three other subjects are passed
{
if(maths >= 50)
passCount++;
if(lifeOr >= 50)
passCount++;
if(history >= 50)
passCount++;
if(compLit >= 50)
passCount++;
if(geo >= 50)
passCount++;
if(passCount >= 3)
passFail= true;
}
return passFail;

10
COS1511/105/2022

//f. A function awardDistinction to determine which subjects should receive distinctions. A


subject receives a distinction if the mark is 75% and above. A distinction should also be awarded
to the average mark ( Grade12 passed with distinction): if a student has passed the grade and
the average mark is 75% or more. (6)

bool awardDistinction (double marks)


{
bool distGranted;

if (marks >=75)
{
distGranted = true;
}
else
{
distGranted = false;
}
return distGranted;
}

//g. A function codeSymbol, to convert each mark to a corresponding grading symbol (A, B, C,
D, E, F) and a code (7,6,5,4,3,2,1). For example, a student with 80% as a mark will have obtained
a grade symbol of A and a code of 7. The symbol and code should be printed next to the mark in
the student report. The same should be calculated and displayed for the average mark. (10)

void codeSymbol(double codeSymbolMark, int &cCode,string &cSymbol)


{
int size =6;

if ( (codeSymbolMark >= 80) && (codeSymbolMark <=100))


{
cCode =7;
cSymbol = "A";
}
else if ( (codeSymbolMark >= 70) && (codeSymbolMark <=79))
{
cCode =6;
cSymbol = "B";
}

else if ( (codeSymbolMark >=60) && (codeSymbolMark <=69))


{
cCode =5;
cSymbol = "C";
}
else if ( (codeSymbolMark >=50) && (codeSymbolMark <=59))
{
cCode =4;
cSymbol = "D";
}

else if ( (codeSymbolMark >=40) && (codeSymbolMark <=49))


{
cCode =3;
cSymbol = "E";
}
11
COS1511/105/2022

else if ( (codeSymbolMark >=30) && (codeSymbolMark <=39))


{
cCode =2;
cSymbol = "F";
}
else if ( (codeSymbolMark >=0) && (codeSymbolMark <=29))
{
cCode = 1;
cSymbol ="FF";
}
return;
}

//h. Students may use a separate function or display in the main function (4)

void displayReport(string name, string surname, string school,float eng, float maths,
float lifeOr,float history,float compLit, float geo )

{
bool passOutcome;
double minimum, maximum, ave;

int engCode=0,mathsCode=0, lifeOrCode=0,historyCode=0,


compLitCode=0, geoCode=0, aveCode=0;
string engSymbol="",mathsSymbol ="",lifeOrSymbol="",
historySymbol="", compLitSymbol="", geoSymbol="", aveSymbol="";
string outcome=" Failed", distinction=" ";

minMax(eng, maths, lifeOr,history, compLit, geo, minimum,maximum);

ave = calcAverageYearMark(eng, maths, lifeOr,history, compLit, geo);

passOutcome = passOrFail(eng, maths, lifeOr,history, compLit, geo);

if (passOutcome)
{
outcome =" Passed";
if ( awardDistinction (ave) )
{
distinction= " with Distinction";
}

}
//Generate the relevant code and symbol according to the subject mark
codeSymbol( eng, engCode, engSymbol);
codeSymbol( maths, mathsCode, mathsSymbol);
codeSymbol( lifeOr, lifeOrCode, lifeOrSymbol);
codeSymbol( history, historyCode, historySymbol);
codeSymbol( compLit, compLitCode, compLitSymbol);
codeSymbol( geo, geoCode, geoSymbol);

codeSymbol( ave, aveCode, aveSymbol);

cout<<"***************************************************"<<endl;
cout<<" STUDENT ACADEMIC RECORD "<< endl;
cout<<" This program inputs the learner marks of matric level "<<endl;
cout<<" subjects and prints the student final report. "<<endl;
cout<<"***************************************************"<<endl;
cout<<" Name: "<<name <<" "<<surname<<" ";
12
COS1511/105/2022

cout<<" School: "<< school<<endl;


cout<<""<<endl;
cout<<"Subject Mark Symbol Code Results "<<endl;

cout<< "English "<<eng<<"% "<<engSymbol<<" "<<engCode<<endl;


cout<< "Mathematics "<<maths<<"% "<<mathsSymbol<<" "<<mathsCode<<endl;
cout<< "Life Orientation "<<lifeOr<<"% "<<lifeOrSymbol<<" "<<lifeOrCode<<endl;
cout<< "History "<<history<<"% "<<historySymbol<<" "<<historyCode<<endl;
cout<< "Computer literacy "<<compLit<<"% "
<<compLitSymbol<<" "<<compLitCode<<endl;

cout<< "Geography "<<geo<<"% "<<geoSymbol<<" "<<geoCode<<endl;

cout<<"Average Year Mark:"<<ave<<"% with Symbol "<<aveSymbol

<<" and code "<<aveCode<<endl;


cout<<""<<endl;
cout<<"Outcome : the student has "<<outcome<<" "<< distinction<<endl;

cout<<"The highest mark obtained was "<<maximum<<endl;


cout<<" The lowest mark obtained was "<<minimum<<endl;
cout<<" ***************************************************"<<endl;

//______________MAIN _FUNCTION______________
int main()
{

float engM, mathsM, lifeOrM,historyM, compLitM, geoM;


string nameM,surnameM, schoolM;

cout << "School Report \n";


studentDetails(nameM, surnameM, schoolM);
getMarks(engM, mathsM, lifeOrM,historyM, compLitM, geoM);

displayReport(nameM, surnameM, schoolM,engM,mathsM,lifeOrM, historyM, compLitM, geoM);


return 0;

The following could be an alternate solution using arrays. (The above solution may not be the only way
to do it).
In the solution below we use four parallel arrays:

subjects[6] marks[6]
subject[0]=>”English” marks[0]=>marks for English
subject[1]=>”Maths” marks[1]=>marks for Maths
subject[2]=>”Life Orientation” marks[2]=>marks for Life Orinetation
subject[3]=>”History” etc.
subject[4]=>”Coumputer Literacy”
subject[5]=>”Geography”

passCode[6] passCodeSymbol[6]
passcode[0]=>the code indicating the result for Eng passCodeSymbol[0]=>the symbol for the result of Eng
passcode[1]=>the code indicating the result for Maths passCodeSymbol[1]=>the symbol for the result of Maths
etc etc

13
COS1511/105/2022

Note the functions called from within the display(). Since the question did not specify that these functions
should be called from main() we have used this logic so as to avoid passing a lot of values to the display()
function from the main().

#include<iostream>
using namespace std;

void studentDetails (string &fullName, string &schoolName)


{
cout << "Enter the learner's full name : "<<endl;
getline(cin, fullName, '\n');
cout << "Enter your School Name :"<<endl;
getline(cin, schoolName, '\n');
return;
}

void getMarks(string subjects[], float marks[])


{
for(int i = 0; i < 6; i++)
{
//validate the marks
do
{ cout << "Enter your mark for " << subjects[i] << ": " <<endl;
cin >> marks[i];

if(marks[i] < 0 || marks[i] > 100)


cout << "Invalid mark! Please Enter a mark for "
<< subjects[i] << " between 0 and 100 : ";
}while(marks[i] < 0 || marks[i] > 100);

}
}

float calcAverageYearMark(float marks[])


{
float total = 0, average =0.0;
int count = 6;// number of subjects

for(int i = 0; i < count; i++)


{
total += marks[i];// add subject marks to get the combined total
}
average = total/count; // calculate the average as the combined total for all the subjects
divided by the number of subjects

return average;// return the value to Main


}

void minMax(float marks[],float &cMini, float &cMaxi)


{
double mini, maxi;
int size = 6;

mini= marks[0];
maxi = marks[0];

for(int i = 1; i < size; i++)

14
COS1511/105/2022

{
if(marks[i] < mini)
mini = marks[i];

if(marks[i] > maxi)


maxi = marks[i];
}
cMini = mini;

cMaxi = maxi;
return;
}

bool passOrFail (float marks[])

{
bool passFail = false;
int numPass = 0;

if( marks[0] < 50)/ /if mark for English less than 50
{
passFail= false;
}
else //check if four subjects are passed,English already passed if control gets to this else
{
for(int i = 1; i < 6; i++)
{
if(marks[i] >= 50)

numPass++;
}
if(numPass >= 3)

passFail= true;
}

return passFail;

bool awardDistinction (double marks)


{
bool distGranted;

if (marks >=75)
{
distGranted = true;
}
else
{
distGranted = false;
}
return distGranted;
}

15
COS1511/105/2022

void codeSymbol(float mark, int &pCode, string &pCodeSymbol)


{
if ( (mark >= 80) && (mark <= 100))
{
pCode = 7;
pCodeSymbol = "A";
}
else if ( (mark >= 70) && (mark <= 79))
{
pCode = 6;
pCodeSymbol = "B";
}

else if ( (mark >= 60) && (mark <= 69))


{
pCode = 5;
pCodeSymbol = "C";
}
else if ( (mark >= 50) && (mark <= 59))
{
pCode = 4;
pCodeSymbol = "D";
}

else if ( (mark >= 40) && (mark <= 49))


{
pCode = 3;
pCodeSymbol = "E";
}
else if ( (mark >= 30) && (mark <= 39))
{
pCode = 2;
pCodeSymbol = "F";
}
else if ( (mark >= 0) && (mark <= 29))
{
pCode = 5;
pCodeSymbol = "FF";
}
return;
}

void display(string fullName, string schoolName,


string subjects[],float marks[], int passCode[],
string passCodeSymbol[], float ave)
{
int aveCode;
string aveSymbol;
int arrSize = 6;
string outcome=" Failed", distinction=" ";
float minimum, maximum;
bool subPass;

//set precision to zero decimal places


cout.precision(0);
cout.setf(ios::fixed);

cout<<"***************************************************"<<endl;
cout<<" STUDENT ACADEMIC RECORD "<< endl;
cout<<" This program inputs the learner marks of matric level "<<endl;
16
COS1511/105/2022

cout<<" subjects and prints the student final report. "<<endl;


cout<<"***************************************************"<<endl;
cout<<" Name: "<< fullName <<" ";
cout<<" School: "<< schoolName<<endl;
cout<<""<<endl;
//use setw() to set the width of the text for alignment purposes
cout<< left << setw(20) <<"Subject Mark Symbol Code "<<endl;
for(int i = 0; i < arrSize; i++)
{
cout << left << setw(20) << subjects[i] << marks[i] << "% "

<< passCodeSymbol[i] << " " << passCode [i] <<endl;


}

codeSymbol( ave, aveCode, aveSymbol); // calling the function here to determine the code
and code symbol on average mark

cout<<"Average Year Mark:"<<ave<<"% with Symbol "

<<aveSymbol<<" and code "<<aveCode<<endl;


cout<<""<<endl;

subPass = passOrFail(marks);

if (subPass)
{
outcome =" Passed";
if ( awardDistinction (ave) ) //calling the function to determine distinction
{
distinction= " with Distinction";
}

}
cout<<"Outcome : the student has "<<outcome<<" "<< distinction<<endl;

minMax(marks, minimum, maximum);


cout <<"The highest mark obtained was "<<maximum<<endl;
cout <<" The lowest mark obtained was "<<minimum<<endl;
cout <<" ***************************************************"<<endl;

return;

//______________MAIN _FUNCTION______________
int main()
{
float ave;

const int NUMSUB = 6;


float marks[NUMSUB];

int passCode[NUMSUB]; //to store the pass code for each subject
string passCodeSymbol[NUMSUB]; //to store the pass code symbol for each subject

string subjects[NUMSUB] = {"English", "Maths","Life Orientation",


"History","Computer Literacy", "Geography"};

string fullName, schoolName, outcome;

17
COS1511/105/2022

cout << "School Report \n";


studentDetails(fullName, schoolName);
getMarks(subjects,marks);
ave = calcAverageYearMark(marks);

//Generate the relevant code and symbol according to the subject mark
//call the function six times, on each subject mark
for(int i = 0; i < NUMSUB; i++)
codeSymbol(marks[i], passCode[i], passCodeSymbol[i]);

//call the display function and display the output


display(fullName, schoolName, subjects, marks, passCode, passCodeSymbol, ave);

Question 3 10
Draw variable diagrams for the following program with input values 2 (for variable first) and 3 (for
variable second).
Note : Refer to Lesson 23 of the Study Guide and go through the activities to figure out how the execution
flows in a program like this where the main() calls other functions. Follow the conventions specified in
the Study Guide when you draw the variable diagrams.
For instance:
• A ? shows an uninitialised value for a variable.
• The notation 25  5 means that execution jumps from line 25 to line 5.
• We use square brackets [ ] around the name of a variable to show that it is inaccessible while the
current function is being executed.
18
COS1511/105/2022

#include <iostream>
2 using namespace std;
3
4 void multiplyBy2(int firstP, int secondP)
5 {
6 firstP = firstP * 2;
7 secondP = secondP * 2;
8 }
9
10 void multiplyBy3(int & firstP, int & secondP)
11 {
12
13 firstP = firstP * 3;
14 secondP = secondP * 3;
15 }
16
17 int main()
18 {
19 int first, second;
20 cout << "Enter the first number: "<< endl;
21 cin >> first;
22 cout << "Enter the second number:" << endl;
23 cin >> second;
24 multiplyBy2(first, second);
25 multiplyBy3(first, second);
26 cout << "The first number is "<< first << " now." << endl;
27 cout << "The second number is " << second << " now." << endl;
28
29 return 0;
30 }

19
COS1511/105/2022

Answer:

11 lines

½ mark each for first two lines


1 mark each for the rest

first second
Line 19 ? ?
first second
Line 21
2 ?
first second
Line 23
2 3
[first] [second] firstP secondP
Line 24->4
2 3 2 3
[first] [second] firstP secondP
Line 6
2 3 4 3
[first] [second] firstP secondP
Line 7
2 3 4 6
first second
Line 8->24
2 3
[first]|firstP [second]|secondP
Line 25>10
2 3
[first]|firstP [second]|secondP
Line 13
6 3
[first]|firstP [second]|secondP
Line 14
6 9
first second
Line 15->25
6 9

©
UNISA
2022

20

You might also like