COS1512 STUDY GUIDE 2023
Study Guide Solutions cos1511 and extras Science (Myers Park High School) lOMoARcPSD| Tutorial letter 102 Introduction to Programming 1 COS1511 Semesters 1 & 2 School of Computing IMPORTANT INFORMATION: This tutorial letter contains the answers to the exercises in the study guide. lOMoARcPSD| 2 TUTORIAL MATTER Up to now you should have received the material listed below. If not, please download it from myUnisa immediately (see below) and also contact the Department of Despatch by sending a sms including your query and student number to 43579, or email . Study Guide DISK 2014 (with software ) Tutorial letters COSALLF/301/4/2014 General information concerning the School and study at Unisa COS1511/101/3/2014 Information about COS1511 Assignments COS1511/102/3/2014 (this letter) Please note the following For e-mail, use the module address namely if you are registered for the first semester and if you are registered for the second semester. Web addresses for downloading of tutorial matter You need AT LEAST 8 hours study time per week for this module. Other contact numbers (include your student number in your enquiry) For enquiries about registration, send a sms to 43578 To contact the assignment or examination section, send a sms to 43584 If you do not receive your study material, send a sms to 43579 For problems with myUnisa, send a sms to 43582 For academic queries in the School of Computing, email the lecturer – see myUnisa. For any non-academic query you may also send and email to Afrikaanssprekende studente: Studiemateriaal vir COS1511 is slegs in Engels beskikbaar. As enigiets onduidelik is, is u baie welkom om ons te kontak. Your programs need not be identical to ours. It is, however, important that your programs yield the correct results (thus extensive testing is essential) and that you use good programming style as explained in the Study Guide. You should, for example, use meaningful names for variables, constants, functions, etc, indent your code correctly, include comments, declare constants where appropriate, avoid the use of global variables, use the correct types of functions as well as the correct types of parameters. lOMoARcPSD| COS1511/102 3 LESSON 1 Exercise 1.1 We repeat the program here: #include <iostream> using namespace std; int main( ) { cout << "Hello world"; return 0; } Descriptive Comment: There is no descriptive comment. StandardHeaderFile : iostream StatementSequence : cout << "Hello world"; return 0; Exercise 1.2 //A poem #include <iostream> using namespace std; int main( ) { cout << "Twinkle, twinkle, little bat!" << endl; cout << "How I wonder what you're at?" << endl; cout << "Up above the world you fly," << endl; cout << "Like a tea-tray in the sky." << endl; return 0; } LESSON 2 Exercise 2.1 (i) ((80 / 5) + (70 / 6)) | | 16 + 11 | 27 (ii) ((-5 + -4) - -3) | -9 - -3 | -6 lOMoARcPSD| 4 (iii) (((6 * 7) / 8) * 9) | 42 / 8 * 9 | 5 * 9 | 45 (iv) ((1 - 2) + ((3 / 4) * 5)) | | -1 + 0 * 5 | -1 + 0 | -1 (v) ((-1 + (23 / -4)) + 56) | -1 + -5 + 56 | -6 + 56 | 50 Exercise 2.2 //Lesson 2 Exercise 2.2 //display number of seconds in a minute, hour, day and year #include <iostream> using namespace std; int main() { cout << "The are 60 seconds in a minute." << endl; cout << "The are " << 60 * 60 << " seconds in an hour." << endl; cout << "The are " << 60 * 60 * 24 << " seconds in a day." << endl; cout << "The are " << 60 * 60 * 24 * 365 << " seconds in a year." << endl; return 0; } Exercise 2.3 //Lesson 2 Exercise 2.3 #include <iostream> using namespace std; int main( ) { cout << "The remainder of 234 divided by 13 is "; Downloaded by Thomas Mboya () lOMoARcPSD| COS1511/102 5 cout << 234 - (234 / 13) * 13 << endl; return 0; } The round brackets are not necessary but their use makes the program more readable. LESSON 3 Exercise 3.1 //Inputs three numbers and displays them in reverse order #include <iostream> using namespace std; int main( ) { int i, j, k; cout << "Enter three numbers: "; cin >> i >> j >> k; cout << "In reverse: " << k << " " << j << " " << i << endl; return 0; } Exercise 3.2 (i) Enter values for variables x, y and z: 2 6 4 x + y / z is 3 x % z is 2 y * z / x + 2 is 14 (ii) Enter values for variables x, y and z: 5 1 3 x + y / z is 5 x % z is 2 y * z / x + 2 is 2 (iii) If 2 6 4 are entered: y * (z / x + 2) is 24 If 5 1 3 are entered: y * (z / x + 2) is 2 Exercise 3.3 //Fahrenheit to Celsius conversion #include <iostream> using namespace std; int main( ) { int fahrenheit; cout << "Enter the temperature in Fahrenheit: "; cin >> fahrenheit; cout << "Celsius = " << 5 *(fahrenheit - 32) / 9 << endl; return 0; } lOMoARcPSD| 6 LESSON 4 Exercise 4.1 //Fahrenheit to Celsius conversion (version for lesson 4) #include <iostream> using namespace std; int main( ) { int fahrenheit, celsius; cout << "Enter the temperature in Fahrenheit: "; cin >> fahrenheit; celsius = 5 * (fahrenheit - 32) / 9; cout << "Celsius = " << celsius << endl; return 0; } Exercise 4.2 //How many boxes? #include <iostream> using namespace std; int main( ) { int items, itemsPerBox, boxes, remainder; cout << "How many items to be packed? "; cin >> items; cout << "How many items fit in a box? "; cin >> itemsPerBox; boxes = items / itemsPerBox; remainder = items % itemsPerBox; cout << "You will need " << boxes << " boxes." << endl; cout << "There will be " << remainder << " items left over." << endl; return 0; } Exercise 4.3 int n = 10; // 10 n += 3; // 13 n /= 2; // 6 n++; // 7 n %= 4; // 3 n -= 5; // -2 The final value of n is -2. LESSON 5 Exercise 5.1 j k m n Line 7: ? ? ? ? j k m n Line 8: 3 ? ? ? Downloaded by Thomas Mboya () lOMoARcPSD| COS1511/102 7 j k m n Line 9: 3 2 ? ? j k m n Line 10: 3 2 1 ? j k m n Line 11: 3 2 1 6 j k m n Line 12: 3 2 1 6 j k m n Line 13: 9 2 1 6 j k m n Line 14: 9 3 1 6 j k m n Line 15: 9 3 1 6 The exact output is: 3 2 1 6 9 3 1 6 Exercise 5.2 1 //Think of a number 2 #include <iostream> 3 using namespace std; 4 5 int main( ) 6 { 7 const int NUMBER = 40; 8 int answer; 9 cout << "Think of a number between 30 and 50. Write it down" << endl; 10 cout << "Then do the following calculations on paper:" << endl << endl; 11 ( ); 12 cout << "Double it" << endl; 13 ( ); 14 answer = NUMBER * 2; 15 cout << "Add 29 to this" << endl; 16 ( ); 17 answer += 29; 18 cout << "Double the result again" << endl; 19 ( ); 20 answer *= 2; 21 cout << "Subtract the original number from your answer" << endl; 22 ( ); 23 answer -= NUMBER; 24 cout << "Divide the answer by your original number and throw away any remainder" << endl; 25 ( ); 26 answer /= NUMBER; 27 cout << "Your final answer is " << answer << endl; 28 return 0; 29 } lOMoARcPSD| 8 NUMBER answer Line 7: 40 ? NUMBER answer Line 14: 40 80 NUMBER Answer Line 17: 40 109 NUMBER Answer Line 20: 40 218 NUMBER answer Line 23: 40 178 NUMBER answer Line 26: 40 4 LESSON 6 Exercise 6.1 //Calculates the area of a room given its length and width #include <iostream> using namespace std; int main( ) { float length, width, area; //Prompt for and input the measurements of the room cout << "Enter the width of the room: "; cin >> width; cout << "Enter the length of the room: "; cin >> length; //Calculate the area area = width * length; //Fixed-point notation, 3 digits after the decimal point (ios::fixed); sion(3); //Display the result cout << endl << "The area of the room is "; cout << area << " square metres." << endl; return 0; } Exercise 6.2 //Calculates the area of a room as well as the cost of a carpet #include <iostream> using namespace std; int main( ) Downloaded by Thomas Mboya () lOMoARcPSD| COS1511/102 9 { const float PRICE_PER_METRE = 59.50; float length, width, area, price; //Prompt for and input the measurements of the room cout << "Enter the width of the room: "; cin >> width; cout << "Enter the length of the room: "; cin >> length; //Calculate the area and the total price area = width * length; price = area * PRICE_PER_METRE; //Fixed-point notation (ios::fixed); //Display the area (3 digits after the decimal point) sion(3); cout << endl << "The area of the room is "; cout << area << " square metres." << endl; //Display the total price (2 digits after the decimal point) sion(2); cout << "The total price is R" << price << endl; return 0; } Exercise 6.3 (i) Implicit conversions take place in line 13 (when the integer quotient of the integers w and x is assigned to the floating point variable y), line 14 (when the value of the floating point variable y is subtracted from the integer value of w), and twice in line 16 (when firstly the quotient of the floating point variable y and the integer x is found and secondly when the integer value of the right-hand side of the assignment statement is stored in the floating point variable answer). Explicit conversions take place in lines 15 and 16. (ii) The value of result will be 11, and the value of answer will be 3. Exercise 6.4 Enter three floating point numbers: 14.0 1.123 64.9999 14 1.123 65 Enter two more floating point numbers: 73.46 27.2727 27.273 73.460 65.000 lOMoARcPSD| 10 LESSON 7 Exercise 7.1 (i) x + y is 579 (ii) x + y is (iii) x + y is c In part (iii), the character '1' is stored in x and the character '2' is stored in y. In the statement z = x + y , these character values are implicitly converted to the numerical values 49 and 50 (the ASCII codes of '1' and '2', respectively) and then added to give 99. This number is then implicitly converted to the character with ASCII code 99, namely the character 'c'. Exercise 7.2 //Determines the position of a letter in the alphabet #include <iostream> using namespace std; int main( ) { char letter; int position; cout << "Enter an upper case letter: "; cin >> letter; position = letter - 'A' + 1; cout << letter << " is in position " << position << " in the alphabet" << endl; return 0; } Exercise 7.3 //Performs a spoonerism #include <string> #include <iostream> using namespace std; int main( ) { string word1, word2, spoonerism; char letter1, letter2; cout << "Enter two words: "; cin >> letter1 >> word1 >> letter2 >> word2; spoonerism = letter2 + word1 + ' ' + letter1 + word2; cout << "Spoonerised that is " << spoonerism << endl; return 0; } Exercise 7.4 //Dialogue generator #include <iostream> #include <string> using namespace std; int main( ) { string name1, name2, colour, noun, adjective; Downloaded by Thomas Mboya () lOMoARcPSD| COS1511/102 11 int number; cout << "Enter a person's name: "; cin >> name1; cout << "Enter another person's name: "; cin >> name2; cout << "Enter a colour: "; cin >> colour; cout << "Enter a number: "; cin >> number; cout << "Enter a noun: "; cin >> noun; cout << "Enter an adjective: "; cin >> adjective; cout << "nDialogue" << endl; cout << "========" << endl; cout << name1 << ":t"Couldn't you see that the traffic light was " << colour << "?"" << endl; cout << name2 << ":t"But I had " << number << " people and a " << noun << " in the car with me."" << endl; cout << name1 << ":t"That is so " << adjective << "! You could have had them all killed."" << endl; return 0; } Exercise 7.5 With the knowledge that you have acquired up to now, it is impossible to do this exercise as it was stated. It is essential to use a loop, but loops have not been discussed yet. (However, if one knows beforehand that 10000 will be entered when the program prompts one to enter a number, one may include 10000 cout statements in the program!) //Computer punishment #include <iostream> #include <string> using namespace std; int main( ) { int n; string s; cout << "Computer punishment" << endl; cout << "-------------------" << endl; cout << "Repetitions? "; cin >> n; ( ); //necessary between cin >> and getline cout << "Message? "; getline(cin, s, 'n'); cout << endl << s << endl; cout << s << endl; cout << s << endl; cout << s << endl; // and so on and so on and so on and so on ... n times return 0; } lOMoARcPSD| 12 LESSON 8 Exercise 8.1 Statement1 is executed in cases (i) and (iv). Exercise 8.2 (i) if (colour == "red") cout << "Correct" << endl; else cout << "No, blood is red." << endl; cout << "What is the colour of the sky? "; cin >> colour; (ii) cout << "Enter salary: "; cin >> parentSalary; if (age < 13) pocketMoney += parentSalary / 20; else pocketMoney += parentSalary / 10; (iii) if (mark < 50) failed++; total += mark; Exercise 8.3 if (balance >= 0) cout << "Credit" << endl; else cout << "Debit" << endl; Exercise 8.4 if (x == y) cout << "x is equal to y" << endl; else cout << "x is not equal to y" << endl; Exercise 8.5 // anyone born before 1945 enters free, others pay R20 int yearBorn; const int CUT_OFF = 1945; const float FEE = 20.0; cout << "When were you born? "; cin >> yearBorn; if (yearBorn < CUT_OFF) cout << "Free entry"; else cout << "Entrance fee R" << FEE; cout << endl; Exercise 8.6 //Will the carpet be large enough? #include <iostream> using namespace std; int main( ) Downloaded by Thomas Mboya () lOMoARcPSD| COS1511/102 13 { float lenth, width, areaFloor, areaNotCovered; const float CARPET_SIZE = 100; cout << "Please enter length of room: "; cin >> lenth; cout << "Please enter width of room: "; cin >> width; areaFloor = lenth * width; if (areaFloor <= CARPET_SIZE) cout << "The carpet will cover the floor." << endl; else { areaNotCovered = areaFloor - CARPET_SIZE; cout << "The carpet is too small. "; cout << areaNotCovered << " square metres will not be covered." << endl; } return 0; } LESSON 9 Exercise 9.1 0 times. If the condition of the while loop is False the very first time the loop is entered, the body of the loop will be skipped. Exercise 9.2 There are two problems. Firstly, the loop control variable count is not changed inside the body of the loop. Its value stays equal to 0 and so the condition (assuming that num is greater than 0) never becomes False. This means that we have an infinite loop. We have to insert the statement count++; into the body of the loop. Secondly, if a value less than or equal to 0 is entered for num, the body of the while loop will never be executed, and thus no value will be assigned to last. We can correct this by replacing the final cout statement with: if (num > 0) cout << "The last value entered was " << last << endl; else cout << "Error: the number of items cannot be zero or less." << endl; So we should have: total = 0.0; cout << "Enter number of values: "; cin >> num; count = 0; while (count < num) { cout << "Enter a value : "; cin >> value; last = value; count++; } if (num > 0) cout << "The last value entered was " << last << endl; lOMoARcPSD| 14 else cout << "Error: the number of items cannot be zero or less." << endl; If the idea was to add all the numbers, we would also have to insert the statement total += value; into the body of the loop after value has been input. Exercise 9.3 //Sipho's money #include <iostream> using namespace std; int main( ) { const float INTEREST = 0.045; const float START_AMOUNT = 1000.00; const float SAVE_AMOUNT = 500.00; const int NUM_YEARS = 18; float balance; int year; //Set the initial values balance = START_AMOUNT; year = 1; //Calculate the accumulation for numYear years while (year <= NUM_YEARS) { balance += balance * INTEREST; balance += SAVE_AMOUNT; year++; } //Display the balance after NUM_YEARS years cout << "The final balance is R" << balance << endl; return 0; } Exercise 9.4 //Can all the luggage be loaded on the airplane? #include <iostream> using namespace std; int main( ) { const int MAX_MASS = 10000; int mass, totalMass; totalMass = 0; cout << "Please enter mass of first piece of luggage (0 to stop): "; cin >> mass; while (mass != 0) { totalMass += mass; cout << "Please enter mass of next piece of luggage (0 to stop): "; cin >> mass; } if (totalMass > MAX_MASS) cout << totalMass << "kg exceeds the permissible maximum load." << endl; lOMoARcPSD| 16 crit2 = (status == 'Y') || (status == 'y'); crit3 = income < 60000; crit4 = ageParent <= 30; if (crit1 && crit2 && crit3 && crit4) cout << "This toddler should be accepted." << endl; else cout << "This toddler should not be accepted." << endl; return 0; } Exercise 11.3 (i) highSchool = grade > 7; (ii) teenager = (age >= 13) && (age <= 19); or teenager = !((age < 13) || (age > 19)); (iii) found = (x >= 0) && (x % 4 == 0); Exercise 11.4 //Guess a number between 1 and 100 in 10 or less tries #include <iostream> using namespace std; int main( ) { const int SECRET = 23; // or any other value between 1 and 100 int guess, numberOfTries; bool found; found = false; numberOfTries = 0; while ((!found) && (numberOfTries < 10)) { cout << "Please enter a guess (1-100): "; cin >> guess; numberOfTries++; if (guess == SECRET) found = true; } if (found) cout << "Well done! You got the number in " << numberOfTries << " guesses." << endl; else cout << "Tough luck! Your 10 guesses are over." << endl; return 0; } LESSON 12 Exercise 12.1 // Is one number equal to the sum of two others? #include <iostream> using namespace std; int main ( ) Downloaded by Thomas Mboya () lOMoARcPSD| COS1511/102 17 { int a, b, c; cout << "Please enter three numbers, a, b and c: "; cin >> a >> b >> c; if ((a + b) == c) cout << "Yes, a + b = c"; else if ((a + c) == b) cout << "Yes, a + c = b"; else if ((b + c) == a) cout << "Yes, b + c = a"; else cout << "No, one number is not equal to the sum of the other two."; cout << endl; return 0; } Exercise 12.2 //Two dice throws #include <iostream> using namespace std; int main( ) { int throw1, throw2, sum; cout << "Please enter 2 numbers representing" << " the throws of a pair of dice: "; cin >> throw1 >> throw2; sum = throw1 + throw2; if ((sum == 7) || (sum == 11)) cout << "You win!"; else if (sum == 2) cout << "Snake eyes!"; else if (sum == 12) cout << "Good shot!"; else cout << "Try again."; cout << endl; return 0; } Exercise 12.3 //Leap year or not #include <iostream> using namespace std; int main( ) { int year; bool leap; leap = false; cout << "Please enter year: "; cin >> year; if ((year % 100) == 0) { Downloaded by Thomas Mboya () lOMoARcPSD| 18 if ((year % 400) == 0) leap = true; } else if ((year % 4) == 0) leap = true; if (leap) cout << year << " is a leap year." << endl; else cout << year << " is not a leap year." << endl; return 0; } Exercise 12.4 //Cereal discount #include <iostream> using namespace std; int main( ) { float amount, discountPerc, finalAmount; cout << "How much did the customer spend? R"; cin >> amount; if (amount < 50) discountPerc = 0.10; else if (amount < 70) discountPerc = 0.20; else if (amount < 100) discountPerc = 0.30; else if (amount < 200) discountPerc = 0.40; else discountPerc = 0.50; finalAmount = amount - discountPerc * amount; (ios::fixed); sion(2); cout << "Amount due is R" << finalAmount << endl; return 0;
Connected book
Written for
Document information
- Uploaded on
- February 10, 2023
- Number of pages
- 66
- Written in
- 2022/2023
- Type
- Exam (elaborations)
- Contains
- Questions & answers
Subjects
- cos1512
- 2023
- cos1512 study guide
- 1512 study guide
- cos1512 study guide 2023
- 1512 study guide 2023
- cos1512 study guide
-
introduction to programming ii
-
cos1512 introduction to programming ii
-
study guide
Document also available in package deal