You are on page 1of 59

BACS1014 PROBLEM SOLVING AND PROGRAMMING

Table of Contents
Tutorial 1....................................................................................................................................2
Tutorial 1_2................................................................................................................................6
Tutorial 2....................................................................................................................................9
Tutorial 3..................................................................................................................................13
Tutorial 4A...............................................................................................................................17
Tutorial 4B...............................................................................................................................23
Tutorial 5..................................................................................................................................28
Tutorial 6..................................................................................................................................31
Tutorial 7..................................................................................................................................34
Tutorial 8A...............................................................................................................................40
Part A – One-dimensional Array......................................................................................................40
BACS1014 PROBLEM SOLVING AND PROGRAMMING

Tutorial 1
1. Define the following terms:
(a) Syntax
Syntax is the spelling or a set of grammar rules of a programming language.

(b) Compiler
Compiler is used to translate a program written in a high-level language to
machine language

(c) Algorithm
Sequence of precise instructions written for computer to solve a problem

2. Describe the following tools and their advantages in planning a program:


(a) Structure chart
Structure chart is a hierarchy chart that shows the relationship between
modules and functional flow through the program. The advantage in planning
a program is it can show how the program is broken into logical steps clearly. It
can show how the program will likely work through this chart and the
interaction between all modules of the program.
(b) Pseudocode
Pseudocode is using English words to convey the program logical. It used in
program design, which is resembling simplified programming. The advantage of
pseudocode is described in precise detail what the program is being designed
to do and the steps can be converted into a computer program.
(c) Flowchart
Flowchart uses standard graphical symbols and connecting lines to represent
the logical flow of data through a program. The advantage in planning a
program is it analyses the program effectively because using flowchart, the
problem can be analysed more efficiently.

3. Differentiate between a structure chart and an organization chart. Provide diagrams to


aid your answer.

Structure chart is a hierarchy chart shows Organization chart is a diagram that


the relationship between modules displays a reporting or relationship
hierarchy which shows the organization
BACS1014 PROBLEM SOLVING AND PROGRAMMING

structure representation positions


4. Draw a flowchart to represent the Pseudocode below:

if code is equal to ‘1’


display “junior”
assign 800.00 to salary
else if code is equal to ‘2’
display “senior”
assign 1200.0 to salary
else
display “Wrong code!”

5. According to this institution exam grading system, design an algorithm by using


Pseudocode to display the GPA (Grade Point Average) based on the total grade points
of the courses and the total credit hours.

Analysis:
1. how to get total grade points
BACS1014 PROBLEM SOLVING AND PROGRAMMING

2. how many courses you take for the particular semester


 4 courses
 BACS1014 – 65marks, 4 credit hours, Grade B, 3.00 = 3.00 * 4 = 12(subtotal)
 BAIT1093 – 80marks, 3credit hours, Grade A, 4.00 = 4.00 * 3 = 12
 BACS1144 – 50marks, 4credit hours, Grade C, 2.00 = 2.00 * 4 = 8
 BAIT1003 – 85marks, 3credit hours, Grade A, 4.00 = 4.00 * 3 = 12
total_grade_point = total_grade_point + subtotal
total_credit_hour = total_credit_hour + credit_hour
GPA = total_grade_point / total_credit_hour

(a) Define the problem by constructing an IPO table.

Input Process Output

number_course 1. get number_courses GPA


s 2. for each course
marks 2.1 get marks
credit_hours 2.2 get credit_hours
2.3 set grade based on marks
2.4 set grade_point based on grade
2.5 subtotal = grade_point * credit_hour
2.6 total_grade_point = total_grade_point +
subtotal
2.7 total_credit_hour = total_credit_hour +
credit_hour
3. GPA= Total Grade Points/Total Credit Hours.
1. Display GPA

(b) Construct a solution outline

(c) Develop the solution into an algorithm.


Find_GPA
START
1. Get number courses
2. For each course
2.1 get marks
2.2 get credit hours
2.3 set grade based on marks
BACS1014 PROBLEM SOLVING AND PROGRAMMING

2.4 set grade_point based on grade


2.5 subtotal = grade_point *credit_hour
2.6 total_grade_point = total_grade_point +subtotal
2.7 total_credit_hour = total_credit_hour + credit_hour
3. GPA = total_grade_point / total_credit_hour
4. Display GPA
END

6. Differentiate between compilation error and runtime error

Compilation error is caused by syntax error. For example, error occurs during
compilation time
Runtime error can be caused by system error(fatal) or program logical error(nonfatal).
For example, error occurs during execution time
BACS1014 PROBLEM SOLVING AND PROGRAMMING

Tutorial 1_2
1. Give THREE (3) reasons of why is it important to provide comments in your code.
Demonstrate in two different ways of writing comments using C++.
The reason to provide comments in code is because the comments will enable other
people to understand the code clearly. Next, the comments can also let the code look
neatly and will reduce the occurrence of errors. Comments also help us to memorize
the logic that we have written the code because it is to track down specific code.

The first way of writing comments is using line comment (single line comments)
which means it can only write one line comment. It is using “//”.
For example:
// This is single line comment
// This is single line comment too

The second way is block comment (multi-line comment) which means there is no
limit for writing the comments, it can write for many lines. It is using “/* and */”.

For example:
/* This is multi-line comment
This is multi-line comment
This is multi-line comment */

2. Identify invalid identifier(s) and explain the reasons why they are invalid.
a) 40Hours (Invalid because cannot begin with digit, must be alphabet or
underscore)
b) year
c) cost_in_$ (Invalid because of special character ‘$)
d) number1
e) include (Invalid because cannot same as keywords)
f) int (Invalid because cannot same as keywords)
g) box-44 (Invalid because cannot include -)
h) Student-name (Invalid because cannot include -)
i) DVD_ROM
j) 2morrow (Invalid because cannot started with number)
k) my_age
l) Get Data (Invalid because no space allowed)
m) Double (Invalid because cannot use data type)
n) A4
o) mark&score (Invalid because of special character ‘&’)
p) first name (Invalid because no space allowed)
q) 5th_Edition (Invalid because cannot begin with digit)
r) Page# (Invalid, illegal symbol ‘#’)
s) C++ (Invalid, illegal symbol ‘++’)
BACS1014 PROBLEM SOLVING AND PROGRAMMING

t) 1stName (Invalid because cannot begin with digit)

3. Write the output of the following segments of code:


(a) cout << "\"\\nnow\"";
Output = “\nnow”

(b) cout << "A1 \"Butch\" Jones";


Output = A1 “Butch” Jones

(c) cout << "\"Hello\\\n Gandalf!";


Output = "Hello\
Gandalif!

4. Briefly explain and correct the error(s) in each of the code segments below.
(a) string word;
cout << "Enter a word: ";
cin << word;

Error: due to the “<<” left shift operator after cin, it should be using the “>>” right
shift in order to collect the input from the line above
Correction:
string word;
cout << "Enter a word: ";
cin >> word;

(b) cout << "Two plus two is " 2+2;

Error: “<<” is missing


Correction:
cout << “Two plus two is” << 2+2;

(c) double invest = 2000.0;


double return = 1.016 * invest;
cout << "The return on your investment of $" << invest
<< " is $" << return;

Error: Cannot use the keyword for the variables


Correction:
double invest = 2000.0, reward = 1.016 * invest
cout << “The return on your investment of $” << invest << “ is $ ” << reward;

(d) int x, y;
cin << x << y;

Error: due to the “<<” left shift operator after cin, it should be using the “>>”
right shift in order to collect the input from the line above
Correction:
int x, y;
BACS1014 PROBLEM SOLVING AND PROGRAMMING

cin >> x >> y;

5. Determine the appropriate data type for the following data:


(a) The average of four marks.
double / float
(b) The number of days in a month.
Integer - int
(c) The length of the Penang Bridge.
double/float
(d) The number of students in your class.
Integer - int
(e) The distance from your house to TAR UC KL in kilometer.
float/double
(f) The single-character prefix that specifies a product type.
Char

6. Code the variable definitions for each of the following:


(a) A character variable named option.
char option;
(b) An integer variable, sum, initialized to 0.
int sum = 0;
(c) A floating-point variable, product, initialized to 1.
double product = 1.0;

7. Write single C++ statement to perform each of the following tasks:


(a) Declare num1, num2, and num3 as integer type variables.
int num1, num2, num3;
(b) Declare tempA, tempB, and tempC as double precision type variables. Initialize
tempA to value 28.9.
double tempB, tempC, tempA = 28.9;
(c) Declare let1 as character type variable and initialize it to value ‘a’.
char let1 = ‘a’;
(d) Declare variable rate as memory constant with value 2.95
const float rate = 2.95;
(e) Assign the letter “B” to the char variable initial.
char initial = ‘B’;
(f) Sends the value in variable name to the stream cout
cout << name;
BACS1014 PROBLEM SOLVING AND PROGRAMMING

Tutorial 2
1. Write the output for each of the following segments of code.
a. int x = 7;
int y = 3;
cout << x/y << " and " << x%y;

Output = 2 and 1

b. double b = 5;
cout << b/2 << (int) b%2;

Output = 2.51

c. int x = 2;
double y = 3.0;
cout << setprecision(2);
cout << x * y << " and " << x / y;

Output = 6 and 0.67

d. double a = 5.5;
cout << (int) a / 2 << "\n";
cout << setprecision(2) << a;

Output = 2
5.5

2. Briefly explain and correct the error(s) in each of the code segments below.
(a) int a = 5;
int double = 2*a;
int triple = 3*a;
cout << "Doubling 5 gives " << double << " and tripling gives "
<< triple;

Double is a reserved keyword. Need to change it to the another name.


double → twice

(b) int x, y;
cin << x << y;
cout << "x = " << x << "\ny = " << y;

When using cin to input data should use “≫” instead of “≪”
cin ≫ x ≫ y

3. Suppose x, y, and z are int variables and x = 2, y = 5, and z = 6. What


is the output of each of the following statements?
(a) cout<<"x = "<<x<<", y = "<<y<<", z = "<<z<<endl;
Ans: x = 2, y = 5, z = 6
(b) cout<<"x + y = "<<x + y<<endl;
Ans: x + y = 7
BACS1014 PROBLEM SOLVING AND PROGRAMMING

(c) cout<<"Sum of "<<x<<" and "<<z<<" is "<<x+z<<endl;


Ans: Sum of 2 and 6 is 8

(d) cout<<"z / y = "<<z / y<<endl;


Ans: z / y = 1
(e) cout<<"2 times "<<x<<" = "<<2*x<<endl;
Ans: 2 times 2 = 4

4. Write a single cout statement that prints the text below.


Krodo says:
"I ♥ YOU!"

(Hint: The heart is given by the escape character \3.)

cout << "Krodo says:\n\"I \3 YOU!\"";

5. The program below is supposed to compute the average of two numbers. The program
compiles without error, but does not correctly compute the average. Describe the logic
error(s) and write the corrected lines. You do not need to rewrite the entire program. The
line numbers are written along the left column to help you write your answer; they are not
part of the program code. Make as few changes as possible.

Line no. Wrong code Correction


Line 5 int total; No initialization
int total = 0;
Line 13 total = total + a Should not be “a”
total = total + b
Line 14 double average = total / 2 Apply next type cast
double average = (double)
total / 2

6. Write the output for the following program statements (which are not related to one
another) (Note: Show all blank spaces with the symbol ):
(a) cout<<setw(10)<<”ABC”;
ABC
BACS1014 PROBLEM SOLVING AND PROGRAMMING

(b) cout<<setfill(‘#’)<<setw(10)<<”ABC”;
#######ABC

(c) cout<< left << setfill(‘@’) << setw(6) << “ABC”;


ABC@@@
(d) cout<<fixed<<setprecision(2)<<123.456;
123.46
(e) cout<<setprecision(7)<<showpoint<<123.45;
123.4500
(f) cout<<setprecision(5)<<123.5748<<endl<<setprecision(6)<<
123.5748;
123.57
123.575

7. Draw a flowchart and write a C++ program that will read 4 integers through a single cin
function. Then, calculate and display the sum (add up all the integers) and product (multiply
all the integers) of these values. Set the field width of the output values to be 10. The
following is the example output:

IPO Table
Input Process Output
num1 1. Prompt for 4 integers sum
num2 2. Get 4 integers product
num3 3. Calculate sum
num4 4. Calculate product
5. Display sum
6. Display product

Flowchart
BACS1014 PROBLEM SOLVING AND PROGRAMMING

Programming
#include <iostream>
#include<iomanip>
using namespace std;

int main() {
// Declare variable
int num1, num2, num3, num4;
double sum = 0.0, product = 0.0;

// Prompt for 4 integers


cout << "Enter 4 integers > ";

// Get 4 integers
cin >> num1 >> num2 >> num3 >> num4;

//Calculate sum_num
sum = num1 + num2 + num3 + num4;

// Calculate product_num
product = num1 * num2 * num3 * num4;

// Display result
cout << left << setw(15) << "Sum of all " << ": "
<< right << setw(10) << sum_num << "\n";
cout << left << setw(15) << "Product of all " << ": "
<< right << setw(10) << product_num << "\n";

return 0;
}
BACS1014 PROBLEM SOLVING AND PROGRAMMING

8. Nicholas wrote a program that computes the average of two integers entered by the
user. The program compiles, but doesn't seem to produce the correct results. The part
of Nicholas’ code that computes the average is shown below.
int num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
cout << "The average is " << (num1+num2)/2;

Explain what is wrong with Nicholas’ code and suggest how to fix it. Demonstrate
your solution.

-The int data type will automatically remove the floating point of the average result.
-Add explicit double data type before (num1+num2) to make sure the average can be
obtained accurately.

cout << "The average is " << static_cast<double>(num1+num2)/2;


BACS1014 PROBLEM SOLVING AND PROGRAMMING

Tutorial 3
1. What are the outputs for the following expressions? [ASCII Code]
(a) ‘A’ < ‘B’
65 < 66 (True)
(b) ‘a’ == ‘A’
97 == 65 (False)
(c) ‘a’ < ‘B’
97 < 66 (False)

2. If int1 = 12, int2 = 18, and int3 = 21, what is the result of each of the following
Boolean expressions?
(a) int1 < int2 && int2 < int3
12 < 18 AND 18 < 21
T AND T
Ans: True
(b) int1 < int3 || int3 < int2
12 < 21 OR 21 < 18
T OR F
Ans: False
(c) int1 <= int2 – 6
12 <= 18 – 6
12 <= 12
Ans: True
(d) int2 <= int1 + 5 || int3 >= int2 + 5
18 <= 12 + 5 OR 21 >= 18 + 5
18 <= 17 OR 21 >= 23
F OR F
Ans: False
(e) !(int1 < 30)
NOT (12 < 30)
NOT (T)
Ans: False
(f) !(int2 == int1 && int3 == int1)
NOT (18 == 12 AND 21 == 12)
NOT ( F AND F )
NOT (F)
Ans: True
(g) !(int1 > 25) && !(int2 < 17)
NOT (12 > 25) AND NOT (18 < 17)
NOT (F) AND NOT (F)
T AND T
Ans: True
BACS1014 PROBLEM SOLVING AND PROGRAMMING

3. What is the result for each of the following expression?


(a) 1 + 2 * 4/2
= 1 + 8/2
= 1 + 4
= 5
(b) (1 + 2) * 4/2
= 3 * 4/2
= 12/2
= 6
(c) 9 % 2 + 1
= 1 + 1
= 2
(d) (1 + (10 – (2+1)))
= (1 + (10 – 3))
= (1 + 7)
= 8
(e) 557 % 8 * 3 – 9
= 5 * 3 – 9
= 15 – 9
= 6
(f) (234/5) * 4 – 7 % 3
= 46 * 3 – 7 % 3
= 184 – 7 % 3
= 184 – 1
= 183

4. Give the value of a, b and c after each statement is executed when we declared variables as
below:
int a, b = 4, c = 0;

(a) a = ++b - ++c;


a b c
4 0
4 5 1

(b) a = b-- + --c;


a b c
4-- 0
3 3 -1

(c) a = b++ + ++c;


a b c
4++ 0
5 5 1

(d) b = a = c--;
a b c
0 0 0
0 0 -1
BACS1014 PROBLEM SOLVING AND PROGRAMMING

5. Given the following definitions, which of the following statements are valid assignments?

#define NUM 20
int a, b = 8;
(a) a = 6; valid
(b) b = 3; valid
(c) a = b =24; valid
(d) a = 12 = b; invalid
(e) b = b + 3; valid
(f) b = 1 + NUM; valid
(g) 9 = b; invalid
(h) b % = 2; valid
(i) a + b = 36; invalid
(j) b * = 10 – b; valid

6. If initially x = 3, y = 4, z = 5, what is the value of each of the following expressions?


(a) x + 2 / 3 + y
=3+2/3+4
=3+0+4
=7

(b) 2 – (x + z) % 2 + 4
= 2 – (3 + 5) % 2 + 4
=2–8%2+4
=2–0+4
=6

(c) y ++ + z-- + x++


=4+5+3
= 12

(d) x++ - ++y


= 3 – (4 + 1)
= -2

(e) ++x - --z


= (3 + 1) – (5 – 1)
=4–4
=0

(f) --x + ++y – z—


= (3 – 1) + (4 + 1) – 5
=2+5–5
=2

7. If x = -4, y = 5 and z = 0, determine whether the following expressions is TRUE or FALSE.


(a) ! (2 + 7 * y >= z – 4)
! (2 + 7 * 5 >= 0 – 4)
BACS1014 PROBLEM SOLVING AND PROGRAMMING

! (2 + 35 >= -4)
! (37 >= -4)
! (TRUE)
Ans: False
(b) x + 2 || z < (y – 3 ) && y
-4 + 2 || 0 < (5 – 3) && 5
-2 || 0 < 2 && 5
-2 || T && 5
-2 || T
T || T
Ans: True
(c) 3 * x / 4 % y && !z
3 * (-4) / 4 % 5 && !(0)
-12 / 4 % 5 && 1
-3 % 5 && 1
-3 && 1
T && T
Ans: True
(d) y – 2 * z < x * 2 / 3
5 – 2 * 0 < (-4) * 2 / 3
5–0 < (-8) / 3
5 < -2
F
Ans: False

8. Correct the error(s) in each of the code segments below.


(a) if ( 1 < x < 5 )
cout << x;

if (x > 1 && x < 5) {


cout ≪ x;
}

(b) int x;
cin >> x;
if (x%2 = 0)
cout << "You entered an even number.";

int x;
cin ≫ x;
if (x % 2 == 0) {
cout ≪ “You entered an even number.”;
}

(c) string s;
getline(cin,s);
if (s < 10)
cout << "Your phrase is less than 10 letters long.";

string s;
getline(cin,s);
BACS1014 PROBLEM SOLVING AND PROGRAMMING

if (s.size() < 10) {


cout ≪ “Your phrase is less than 10 letters long.”;
}

Tutorial 4A
1. Suppose we take input x as an integer.
int x;
cin >> x;
Write the if statement that runs under the specified condition below. The first one is done
for you as an example.
(a) x is a positive number
if (x > 0)
(b) x is between 3 and 30, including 3 and 30
if (x >= 3 && x <= 30)
(c) x is an even number, not including zero
if (x % 2 == 0 && x != 0)
(d) x is a number that ends with zero, such as 420
if (x % 10 == 0)

2. A company has decided to raise the salaries of its employees. The company will determine
the percent rise based on the status and years of service of each employee.

Employee Literal Years of Service Percent Raise


Status
Full time ‘F’ Less than 7 years 5.0
Full time ‘F’ 7 years or more 7.0
Part time ‘P’ Less than 7 years 3.5
Part time ‘P’ 7 years or more 4.1

Draw a flowchart to determine the percent rise for an employee based on the table above.
Then write a nested if statement using C++. You must include the variable declarations in
your code.
BACS1014 PROBLEM SOLVING AND PROGRAMMING

if (status == ‘F’) {
if (years < 7) {
percent_raise = 5.0;
}
else {
percent_raise = 7.0;
}
}
else if (status == ‘P’) {
if (years < 7) {
percent_raise = 3.5;
}
else {
percent_raise = 4.1;
}
}

3. Explain why the code below is considered inefficient. Demonstrate how it can be improved.
if (expenses < 100.00)
rebate = 0.2;
if (expenses >= 100.00 && expenses < 500.00)
rebate = 0.4;
if (expenses >= 500.00)
rebate = 0.7;

if (expenses < 100.00)


rebate = 0.2;
BACS1014 PROBLEM SOLVING AND PROGRAMMING

else if (expenses < 500.00)


rebate = 0.4;
else
rebate = 0.7

4. Write the C++ code to represent the selection structure below using if-else statements.

if (Group == 1) {
cout ≪ “one” ≪ endl;
if (level == ‘A’) {
cout ≪ “admin” ≪ endl;
}
else if (level == “S”) {
cout ≪ “staff” ≪ endl;
}
else {
cout ≪ “invalid” ≪ endl;
}
}
else if (Group == 2) {
cout ≪ “two” ≪ endl;
}
else if (Group == 3) {
cout ≪ “three” ≪ endl;
}
else {
cout ≪ “invalid” ≪ endl;
}

5. Convert the following if/else sequence to a switch statement.


int x;
cin >> x;
BACS1014 PROBLEM SOLVING AND PROGRAMMING

if (x == 2)
cout << "x=2";
else if (x==3 || x==5) {
cout << "x=3 or 5";
x++;
}
else if (x==4)
cout << "x=4";
else
cout << "Else.";

int x;
cin ≫ x;
switch (x) {
case 2:
cout ≪ “x=2”;
break;
case 3:
case 5:
cout ≪ “x=3 or 5;
x++;
break;
case 4:
cout ≪ “x=4”;
break;
default:
cout ≪ “Else.”;
}

6. Part of the code segments below contains error(s). Identify the errors.
string s;
getline (cin,s);
switch (s) {
case "hello":
cout << "hi";
break;
default:
cout << "bye";
break;
}

Error Explanation Correction


The value s switch cannot accept Change datatype to char
string cin ≫ “s”;

case ‘h’:
BACS1014 PROBLEM SOLVING AND PROGRAMMING

7. Rewrite the following multi-way if-else statement by using a switch statement:


if (character == 'A')
cout << "Hello!";
else if (character == 'B')
cout << "Happy Birthday!";
else if (character == 'C')
cout << "Thank you!";
else
cout << "Welcome!";

switch (character) {
case ‘A’:
cout ≪ “Hello!”;
break;
case ‘B’
cout ≪ “Happy Birthday!”;
break;
case ‘C’
cout ≪ “Thank you!”;
break;
default:
cout ≪ “Welcome!”;
}
8. The code below can be compiled, but it contains run-time error.
int x;
cout << "Enter a number: ";
cin >> x;
switch(x) {
case 1:
cout << "You typed 1.\n";
case 2:
cout << "You typed 2.\n";
default:
cout << "You did not type 1 or 2.\n";
}

(a) What is the error in the code above?


Missing break statement for case 1 and case 2

(b) What is the output of the code if the user types in 1?


You typed 1.
You typed 2.
You did not type 1 or 2.

(c) Demonstrate how the code above can be improved.


int x;
cout << "Enter a number: ";
cin >> x;
switch(x) {
case 1:
BACS1014 PROBLEM SOLVING AND PROGRAMMING

cout << "You typed 1.\n";


break;
case 2:
cout << "You typed 2.\n";
break;
default:
cout << "You did not type 1 or 2.\n";
}

9. Assume that the tuition fee for year 1 and year 4 is RM1200.45 and RM2267.30 respectively
without considering the Code. The fee for year 2 and year 3 is determined by code as shown
in the table below:

Year Code Fee (RM)


1 1200.45
2 or 3 A 1789.00
B 2005.50
Others 2200.90
4 2267.30

Write a nested switch statement to assign the fee value based on the conditions above.

switch (year) {
case 1:
fee = 1200.45;
break;
case 2:
case 3:
switch (code) {
case ‘A’:
fee = 1789.00;
break;
case ‘B’:
fee = 2005.50;
break;
default:
fee = 2200.90;
BACS1014 PROBLEM SOLVING AND PROGRAMMING

}
break:
case 4:
fee = 2267.30;
break;
default:
cout ≪ “Invalid year”;
BACS1014 PROBLEM SOLVING AND PROGRAMMING

Tutorial 4B
1. Identify the syntax/logic error(s) in each of the code snippets below and suggest the
correction(s).
a. //this code should print out the numbers from 1 to 9
int x = 1;
while (x > 10);
{ cout ≪ setw(3) ≪ x;
x ++;
}

Ans:
int x = 1;
while (x < 10)
{ cout ≪ setw(3) ≪ x;
x ++;
}

b. //this code should print out the numbers from 1 to 100


int j = 1;
while (j <= 100)
cout ≪ j ≪ endl;
j++;

Ans:
int j = 1;
while (j <= 100)
{ cout ≪ j ≪ endl;
j++;
}

c. //This code is supposed to display “5! is 120.”


int N = 5;
int factorial = 1;
while (N >= 1) {
factorial = factorial * N;
N--;
cout ≪ “5! is ” ≪ factorial ≪ “.\n”;
}

Ans:
int N = 5;
int factorial = 1;
while (N >= 1) {
factorial = factorial * N;
BACS1014 PROBLEM SOLVING AND PROGRAMMING

N--;
}
cout ≪ “5! is ” ≪ factorial ≪ “.\n”;
2. Assume that Mr. Frodo is developing a game. Once the game ends, the user will be
prompted to check whether they want to play again. Mr. Frodo wanted to ensure that
regardless of whether the user has entered an upper or lower-case "y" as the response,
the game shall be repeated. Therefore, he wrote the while loop as follows:

while (response == "y" && response == "Y")


{
game(); //to execute the game module
}

The program can be compiled, but it doesn't seem to run properly. Explain what the
error is.

while (response == “y” || response == “Y”)


{
game();
cout ≪ “Want to play again?”;
cin ≫ response;
}

The condition must use AND operation. Next, prompt and get the
user response to make sure the while loop can be continued

3. For each of the nested structure below, suggest the appropriate type of selection
statement and loop statement for each of the following program. The first question is
done for you as example.

(a) You would like to print the numbers from 1 to 31 if the user enters “January”,
“March” or “May”; 1 to 28 if “February”; and 1 to 30 if it is “April” or “June”.
Example of answer: Use if-else statement to select the month, use for loop to
display the numbers.

(b) You would like to continuously generate 30 random numbers, and all the numbers
must be unique.
Answer: Use random statement to display random numbers between 1-30,
use while loop to display the numbers continuously. Use if statement to check
whether the number is unique

(c) The user can order food through a system. At first, the user can select an option
from the menu: 1 for Appetizer, 2 for Main Course, 3 for Dessert and 4 for
Payment. Each time the user has selected food from one option, the menu will be
prompted again for his other selection until he chooses option 4.
Answer: Use while loop to prompt the option continuously until the user chooses
option 4. Use switch case for selection food from option
BACS1014 PROBLEM SOLVING AND PROGRAMMING

4. Given the code below, answer the following questions.


1 #include <iostream>
2 using namespace std;
3 int main()
4 { int x=5, y=100;
5 do {
6 x = x +10;}
7 while (x < y);
9 cout ≪ x ≪ “ ” ≪ y ≪ endl;
1
0 return 0;
1 }
1
(a) How many times is the code in Line 6 executed?
10 times
(b) What is the output of the program above?
105 100
(c) Rewrite the above program using a for loop.
#include<iostream>
#include<iomanip>
using namespace std;

int main() {
int y = 100;
int x = 5;
for ( ; x < y; ) {
x = x + 10;
}
cout << x << " "<< y <<endl;
return 0;
}

(d) Explain the difference between a while loop and a do-while loop.
For the while loop, it is making a decision first, if it fulfils the
condition then executes the expression statement. For a do-
while loop, it executes an expression statement, then makes a
decision. Therefore, do-while loop will execute the expression
statement at least one time.

5. What does the following code print out?


a. for (int i=10; i > 5; i--) {
if (i %2 == 0)
cout << 2*i << "a" << endl;
else
cout << i << "b" << endl;
}

i = 10 i>5 i-- i % 2 == 0 cout


10 10 > 5 T 9 10 % 2 == 0 T 2 * 10a = 20a
BACS1014 PROBLEM SOLVING AND PROGRAMMING

9 9>5 T 8 9%2 == 0 F 9b
8 8>5 T 7 8%2 == 0 T 2 * 8a = 16a
7 7>5 T 6 7%2 == 0 F 7b
6 6>5 T 5 6%2 == 0 T 2 * 6a = 12a
5 5>5 F

b. int y = 0;
do {
if (y == 6)
y -= 10;
if (y < 8)
y += 2;
cout << y << " ";
} while (y>0);

y == 6 y = y – 10 y<8 y=y+2 cout


y=0 y == 6 F - 0<8 T y=0+2=2 2
y=2 y == 6 F - 2<8 T y=2+2=4 4
y=4 y == 6 F - 4<8 T y = 4 + 2 =6 6
y=6 y == 6 T y = 6 – 10 = -4 -4 < 8 T y = -4 + 2 = -2
-2
2 4 6 -2

c. What is the output of (b) if


i. int y =9 on Line 1
Unlimited print of digit 9
ii. We changed the do-while loop into a while loop?
No difference, still unlimited print of digit 9

6. Write the output of the following segments of code.


for (int i=1; i<4; i++) {
for (int j=1; j<=i; j++)
cout << j << " ";
cout << "\n";
}

i=1 i<4 i++ j=1 j <= i j++ cout


i=1 1<4T 2 j=1 1 <= 1 T 2 1
j=2 2 <= 1 F \n
i=2 2<4T 3 j=1 1 <= 2 T 2 1
j=2 2 <= 2 T 3 2
j=3 3 <= 2 F \n
i=3 3<4T 4 j=1 1 <= 3 T 2 1
j=2 2 <= 3 T 3 2
j=3 3 <= 3 T 4 3
j=4 4 <= 3 F \n
i=4 4<4F 1
12
123
BACS1014 PROBLEM SOLVING AND PROGRAMMING

7. A for statement as shown below is written in a program


for( ; ; )
{
...
}

(a) Describe the implications behind the null expressions in the for stamen above
for(expr1; expr2; expr3)
expr1: Initialization of control variables
expr2: Loop continuation condition
expr3: Updating (increment / decrement) of control variable.

(b) Suggest how this stamen can be exited


Apply break statement

(c) Is this a good structured programming style? Explain your answer


It is not a good structure. There is no entry point and exit point
BACS1014 PROBLEM SOLVING AND PROGRAMMING

Tutorial 5
1. What is a pointer? How do you declare a pointer variable?
pointer variable also can store different memory address. For example, int
*number_ptr;

2. What unfortunate misinterpretation can occur with the following declaration?


int* int_ptr1, int_ptr2;

declaration looks like two objects of pointer to int because "int*" that give the
thought the variables are bind to the *. int_ptr1 is an int pointer, while int_ptr2 is
ordinary variable

3. What is wrong in the following code


a. int x = 30;
int *pX = x;
cout << “x is ” << x << endl;
cout << “x is ” << px << endl;

Correction
int x = 30;
int *pX = &x;
cout << “x is ” ≪ x ≪ endl;
cout ≪ “x is ” ≪ *pX ≪ endl;

b. double x = 3.0;
int *pX = &x;

Pointer variable can only point to the variable of the same type

4. Give at least two uses of the * operator. State what the * is doing, and name the use of
the * that you present.
a. Dereferencing Operator  Returns the value stored in the variable or stores a
value into the variable through the pointer variable
EG: int num = 10, *ptr = &num;
cout ≪ *ptr;
*ptr = 20;

b. Multiplication operator  Calculate the product of two variables


EG: a * 3
BACS1014 PROBLEM SOLVING AND PROGRAMMING

5. What is the output produced by the following code?


int *p1, *p2;
p1 = new int;
p2 = new int;

*p1 = 10;
*p2 = 20;
cout << *p1 << " " << *p2 << endl; 10 20

p1 = p2;
cout << *p1 << " " << *p2 << endl; 20 20

*p1 = 30;
cout << *p1 << " " << *p2 << endl; 30 20

How would the output change if you were to replace?


*p1 = 30;
With the following?
*p2= 30;

Ans: 30 30

6. What will be the output produced by the following code segment?


a. int a;
int* p;
a = 2;
p = &a;
a = a + 1;
cout ≪ *p;

a=2 p = &a a=a+1 *p = a


=2 =2+1 =3
=3

b. int a;
int* p;
a = 2;
p = &a;
a = a + 2;
cout << *p;

a=2 p = &a a=a+2 *p = a


=2 =2+2 =4
=4
BACS1014 PROBLEM SOLVING AND PROGRAMMING

c. int a;
int b;
int* p;
int* q;
a = 3;
p = &a;
q = p;
*q = *q + 5;
cout << *p;

a=3 p = &a q=p *q = *q + 5 *p = 8


=3 =3 = 3+5
= 8

d. int a;
int* p;
a = 4;
p = &a;
cout << (*p) / a;

a=4 p = &a (*p) / a = 4 / 4


=4 =1
BACS1014 PROBLEM SOLVING AND PROGRAMMING

Tutorial 6
1. Evaluate value of the following sequences
a. fabs (9.5)
9.5
b. fabs (-2.4)
2.4
c. fabs (-7.1)
7.1
d. abs (1)
1
e. abs (-2)
2
f. floor (2.9)
2
g. floor (-1.1)
-2
h. ceil (-1.1)
-1
i. ceil (0.224)
1
j. floor (3.45 * 100 + 0.5) / 100
floor (345.5) / 100
345 / 100
3.45
k. pow (3,4)
81
l. pow (9.0, 3.0 / 2)
27
m. sqrt (144)
12

2. Write the C++ expression that will generate a random number in range of
a. 30 to 50
rand() % 21 + 31
b. 1-10
rand() % 10 + 1
c. 1000-9999
rand() % 9000 + 1000
BACS1014 PROBLEM SOLVING AND PROGRAMMING

3. Define the range of the random numbers generated by the following expressions
a. rand() % 7
0 to 6
b. rand() % 6 + 1
1 to 6
c. rand() % 32 – 10
-10 to 21

4. Write a C++ program that generates a random number from the following set:
a. 1, 2, 3, ……, 40, 41, 42
rand() % 42 + 1
b. 1, 4, 7, 10, 13, 16
rand() % 6 * 3 + 1

5. Evaluate the output of the following expressions:


char X = ‘X’ , Y = ‘Y’ , a = ‘a’ , b = ‘b’ ;
a. isalpha(X)
1
b. isdigit(Y)
0
c. islower(a)
1
d. isupper(b)
0
e. tolower(X);
x
f. toupper(Y);
Y

6. Write the output for each of the following segments of code


a. string name = "Sam Gamgee";
name.erase (3,3);
cout << name << endl;
name.insert (2,"hi");
cout << name << endl;

S a m G a m g e e
0 1 2 3
0 1 2
S a m m g e e
0 1 2
S a h i m m g e e
BACS1014 PROBLEM SOLVING AND PROGRAMMING

Sammgee
Sahimmgee
b. string b = "Gandalf";
cout << b.substr(3,3);
cout << b << endl;
b.insert(0, "Hello ");
cout << b << endl;

G a n d a l f
0 1 2 3
0 1 2
d a l
G a n d a l f
0
H e l l o G a n d a l f

dalGandalf
Hello Gandalf

7. Given the following variable declarations


char a[50] = "BACS 1014";
char b[10] = {'b','a','c','s','\0','1','0','1','4','\0'};
char *p = "Hello";
const char *p1 = "And ";
const char *p2 = "I think to myself.";
char temp[100];

What will be printed when the following C++ statements are performed?

(a) cout << strlen(a) << ", " << strlen(b) << ", " << strlen(p) << endl;
9, 4, 5

(b) strcpy (temp, p2);


cout << temp << endl;
I think to myself
BACS1014 PROBLEM SOLVING AND PROGRAMMING

Tutorial 7
1. Define modularization. Discuss the benefits of modular design in programming
Modularization enables us to organize a program into small, independent modules that are
separately named & individually invoke-able program elements. Each module performs a
separate task with a single purpose.

The benefits of modularization are that it is easier to read and understand the program.
Next, the program will be more manageable and the same code can be used in separate
multiple sections. Besides, it can protect the data which the related data available only if
needed. It also makes the program easy to debug because it can focus and work on the
module easily to find errors.

2. A program is designed to compute a customer’s car rental charges. Every car is charged at
RM25 per day with addition to a charge of RM 0.40 for every kilometre used. Finally, the
final rental charges and the detailed breakdown of charges should be displayed on the
screen.

IPO Table
Input Process Output
days 1. Prompt and get days days
distance 2. Prompt and get distance distance
3. Calculate mileage mileage
4. Calculate rental rental
5. Calculate total_charges total_charges
6. Display all charges

a. Draw a structure chart to represent the division of tasks above.

Car_rantal_system

calculate_total_charges

calculate_rental calculate_mileage print_charges


BACS1014 PROBLEM SOLVING AND PROGRAMMING

b. Based on the structure chart given in (a), draw flowcharts to describe the solution of
each task.

c. Based on the flowchart given in (b), write a program which integrates the necessary
functions as described.
#include <iostream>
#include <iomanip>
using namespace std;

void calculate_total_charges(int, double);


int calculate_rental(int);
double calculate_mileage(double);
void print_charges(int,double,double,double,double);

const double RATE = 0.4;


const int RENT_CHARGE = 25;

int main() {
int days;
double distance;

cout << "Enter number of days: ";


cin >> days;
cout << "Enter distance in KM: ";
cin >> distance;

calculate_total_charges(days, distance);

return 0;
}

void calculate_total_charges(int days,double distance) {


double rental = calculate_rental(days);
double mileage = calculate_mileage(distance);
BACS1014 PROBLEM SOLVING AND PROGRAMMING

double total_charges = rental + mileage;

cout << endl;

print_charges(days, distance, rental, mileage, total_charges);


}

int calculate_rental(int days) {


double rental = (double)days * RENT_CHARGE;

return rental;
}

double calculate_mileage(double distance) {


double mileage = distance * RATE;

return mileage;
}

void print_charges(int days, double distance, double rental, double mileage, double
total_charges) {
cout << "---------------------------------" << endl;
cout << "Days\t\t: " << days << endl;
cout << "Rental\t\t: RM" << rental << endl;
cout << "Distance\t: " << distance << "KM" << endl;
cout << "Mileage\t\t: RM" << mileage << endl;
cout << "Total charges\t: RM" << total_charges << endl;
}

3. Given the code below, answer the following questions.


1 int main()
2 { int n, res=1;
3 cout << "N Factorial: " << endl;
4 do{
5 cout << "Enter a positive number: ";
6 cin >> n;
7 while(n<1);
8 for int i=n; i>0; i--)
9 {
1 res = res * n;
0 }
11 cout << n << "! = " << res << endl;
1 return 0;
2 }
1
3
1
4
a. Suggest how would you modularize the program above. Can you suggest two
modules?
BACS1014 PROBLEM SOLVING AND PROGRAMMING

Get_positive_number
Calculate_result

b. Draw the structure chart to represent the modular design of your program as
suggested in (a).

c. Rewrite the above program based on your design given in (b).


#include<iostream>
using namespace std;

int get_positive_number();
void calculate_result(int);

int n;

int main() {
cout << "N Factorial: " << endl;
n = get_positive_number();
calculate_result(n);

return 0;
}
int get_positive_number() {
do {
cout << "Enter a positive number: ";
cin >> n;
} while (n < 1);

return n;
}
void calculate_result(int num) {
int res = 1;

for (int i = num; i > 0; i--) {


res *= i;
}

cout << num << "! = " << res << endl;
}
BACS1014 PROBLEM SOLVING AND PROGRAMMING

4. Given the following output as shown in Figure 1, answer the following questions
a. Suggest four different modules that are appropriate for the program.
- movie_selection()
- time_selection()
- total_amount()
- payment_balance()

b. Draw the structure chart to represent the modular design of your program as
suggested in (a).

c. Design the Pseudocode for the main program.

d. Produce the definitions of the four functions (modules) you have suggested, and
write the main program that would invoke (call) the four functions. The output of the
main program should be identical as shown in Figure 1.

SUPERSTAR cinema ticketing system


All rights reserved 2013
*************************************
Movie for today:
1. Man of Steel Returns
2. The Dark World of Thor
3. The Hobbyists
BACS1014 PROBLEM SOLVING AND PROGRAMMING

Select movie > 1

Show Time for today:


1. 11.30
2. 14.50
3. 18.00
4. 21.10
5. 12.20 mn

Select time > 1

Price per ticket: RM10.00


Enter number of tickets > 3
Total amount: RM 30.00

Enter payment > 50


Balance: RM 20.00
Remark: Bolded numbers are the inputs by the user
Figure 1: Sample output screen

5. Given the code below, answer the following questions.


1 #include <iostream>
2
3 const int a = 17;
4 int b, c;
5 int main()
6 {
7 b=4;
8 c=6;
9 SomeFunc(42.8);
10 cout << "a = " << a
11 << " b = " << b
12 << " c = " << c;
13
14 return 0;
15 }
16 void someFunc(double c);
17 {
18 double b = 2.3;
19 cout << "a = " << a
20 << " b = " << b
21 << " c = " << c;
22 }
a. The code cannot be compiled. Identify the error.
- Should add “using namespace std;” and “void someFunc(double)” before
constant varaibles
- At line 9, uppercase S should become lowercase s
- At line 16, no semicolon
BACS1014 PROBLEM SOLVING AND PROGRAMMING

b. Assume that the correction in (a) is done properly. What is the output of the
program?
Output: a = 17 b = 2.3 c = 42.8 a = 17 b = 4 c = 6
BACS1014 PROBLEM SOLVING AND PROGRAMMING

Tutorial 8A
Part A – One-dimensional Array
1. Write C++ code segments that fulfil the following criteria.
(a) Write a declaration of an array variable called temps that holds 24 values of type
float.
float temps[24];

(b) Write a for loop that fills every element of the temps array declared with the value
32.0.
float temps[24]

for (int i = 0 ; i < 24 ; i++) {


temps[i] = 32.0
cout << “The value in temps [“ << i << ”] is ≪ temp[i] << endl;
}

2. Write the output of the following blocks of code.


(a) int b[4] = {4,5,2,1};
for (int i=2; i>=0; i--)
cout << b[i] + b[i+1] << "\n";

i=2 [ i >= 0 ] b[i] = b[2] b[i+1] = b[3] b[i] + b[i+1] i -- = 1


2 >= 0 (T) =2 =1 =2+1
=3
i=1 1 >= 0 (T) b[i] = b[1] b[i+1] = b[2] b[i] + b[i+1] i -- = 0
=5 =2 =5+2
=7
i=0 0 >= 0 (T) b[i] = b[0] b[i+1] = b[1] b[i] + b[i+1] i -- = -1
=4 =5 =4+5
=9
i = -1 i >= 0 (F)

Output:
3
7
9

(b) int a[4];


a[0] = 2;
for (int i = 1; i < 4; i++)
a[i] = i + a[i-1];
for (int i = 0; i < 4; i++)
cout << a[i] << " ";

i=1 [i<4] a[i] = a[1] a[i-1] = a[0] a[1] = i + a[i-1] i ++ = 2


1 < 4 (T) =2 =1+2
=3
BACS1014 PROBLEM SOLVING AND PROGRAMMING

i=2 2 < 4 (T) a[i] = a[2] a[i-1] = a[1] a[2] = i + a[i-1] i ++ = 3


=3 =2+3
=5
i=3 3 < 4 (T) a[i] = a[3] a[i-1] = a[2] a[3] = i + a[i-1] i ++ = 4
=5 =3+5
=8
i=4 4 < 4 (F)

Output:
2358

3. Use THREE (3) different ways to declare an 11-element array of characters called
arr_alpha and store in it the alphabets from A to J.
char arr_alpha[10] = {‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘G’, ‘H’, ‘I’, ‘J’};

char arr_alpha[] = {‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘G’, ‘H’, ‘I’, ‘J’};

char arr_alpha[10];
arr_alpha[0] = ‘A’;
arr_alpha[1] = ‘B’;
arr_alpha[2] = ‘C’;
arr_alpha[3] = ‘D’;
arr_alpha[4] = ‘E’;
arr_alpha[5] = ‘F’;
arr_alpha[6] = ‘G’;
arr_alpha[7] = ‘H’;
arr_alpha[8] = ‘I’;
arr_alpha[9] = ‘J’;

4. (a) Declare a character array called name, which contains the string “Programming”.
char name[] = “Programming”;

(b) Display the 5th character of name based on Q4 (a) on screen.


cout << name[4];

(c) Replace the 1st character of name based on Q4 (a) with the letter ‘p’
name[0] = ‘p’;

5. (a) Declare an array, called number, to store 8 integer numbers.


int number[8];

(b) Assign the value 5 to the last element of the array number based on Q5 (a).
number[7] = 5;

(c) Write C++ statements display all integers in the array number and then display its
total and average.
int total = 0
double average = 0.0

for (int i = 0 ; i < 8 ; i ++) {


BACS1014 PROBLEM SOLVING AND PROGRAMMING

cout << number[i] <<endl;


total += number[i];
}
average = (double) total / 8.0
cout ≪ endl;
cout ≪ “Total: ” ≪ total ≪ endl;
cout ≪ “Average: ” ≪ average ≪ endl;

6. (a) Write a declaration for COST, which is an array that can be used to store 10 item cost
prices to two decimal places. Initialize COST to 0.00.
double COST[10] = {0.00};

(b) Write a C++ program segment to read (from the keyboard) the 10 item cost prices into
the array COST.
for (int i = 0 ; i < 10 ; i++){
cin ≫ COST[i];
}

(c) Write a statement to change the fourth item’s price to 8.00.


COST[3] = 8.00;

(d) Assume that the selling prices of the 10 items are stored in an array SELL. Write a C+
+ program segment that creates an array PROFIT to record the profits for the ten items.
Assume that profit equals selling price minus cost price. Display the contents of PROFIT
and the index of the highest profit item.
double SELL[10] = {0.00};
double PROFIT[10] = {0.00};
int highIndex = 0;
double largest;
largest = PROFIT[0];

int main(){
for (int i = 1; i < 10; i++) {
PROFIT[i] = SELL[i] – COST[i];
if(PROFIT[i] > largest) {
largest = PROFIT[i]
highindex = i
}
for(int i = 0;i < 10;i++){
cout ≪ PROFIT[i] ≪ endl;
}

cout ≪ “Highest Index = ” ≪ highindex ≪ endl;

return 0;
}
BACS1014 PROBLEM SOLVING AND PROGRAMMING

7. Suppose list is an array of five elements of the type int. What is stored in list array
after the following C++ codes are executed?
for(i = 0; i < 5; i++) {
list[i] = 2 * i + 5;
if(i % 2 == 0)
list[i] = list[i] – 3;

Output:
2 7 6 11 1

8. What is the output of the following program segment?


int x[] = { 27, 43, 19, 8, 31, 60 };
int a = 1;
cout << x[a] + x[4] << endl;
cout << x[a + a] << endl;
x[a - 1] = x[a];
x[a] = x[a + 1];
cout << x[a] << endl;
cout << x[ (x[ (x[5] - 57) ] - 8) ] << endl;

Output:
74
19
19
43

9. arrNum1 and arrNum2 are two integer type arrays of size 10. Write a program segment
to read 10 integer numbers from the user into arrNum1. Multiply each element of
arrNum1 with its corresponding index and store the value into the corresponding element
of arrNum2.

int arrNum1[10], arrNum2[10];

for (int i = 0; i < 10; i++) {


cin >> arrNum1[i]
arrNum2[i] = arrNum1[i] * i
}

for (int i = 0; i < 10, i++) {


cout ≪ arrNum2[i] ≪ endl;
}

10. The program code below is supposed to display all the values in the value array.
#include <iostream>
using namespace std;

int main()
{
int value[9] = {1,2,3,4,5,6,7,8,9,0};
BACS1014 PROBLEM SOLVING AND PROGRAMMING

int number;

for (number = 9; number >=1 ; number --)


{
cout << value[number] << " ";
}
return 0;
}

(a) Identify the errors in the code. Suggest the corrections to be done.
At line 6, size of the array is wrong and it should be 10. int value[10]
At line 9, array index number wrong and it should be start from 0. number >= 0

(b) Assume that the corrections for the above are accurate, what is the output of the
program above?
0987654321
BACS1014 PROBLEM SOLVING AND PROGRAMMING

Tutorial 8B
Part B – Two-dimensional Array
1. Demonstrate how to store the student information as shown below into two (2) one-
dimensional arrays and one (1) two-dimensional array by using C++ code. Briefly explain
your answers.
Student name Student index
Anne ×1001
Benson ×1039
Cherry ×1142
Donald ×1092
Edison ×1003

One-dimensional array:
string studentName[5] = {“Anne”, “Benson”, “Cherry”, “Donald”, “Edison”};
string studentIndex[5] = {“×1001”, “×1039”, “×1142”, “×1092”, “×1003”}

Two-dimensional array:
sting student[5][2] = {{“Anne”, “×1001”}, {“Benson”, “×1039”}, {“Cherry”,
“×1142”}, {“Donald”, “×1092”}, {“Edison”, “×1003”},

2. Given the following code segment.


int x[2][3] = { {14,3,-5}, {0,46,7} };
(a) Illustrate the array above in a row-column format.

0 1 2
0 14 3 -5
1 0 46 7

(b) Use a nested-for loop to prompt 6 contiguous numbers from the user and assign the
values to the array x.
for (int row = 0; row < 2; row++) {
for (int col = 0; col < 3; col++) {
cout ≪ “Enter number in row ” ≪ row + 1 ≪ “, column ” ≪ col + 1 ≪
“: ”;
cin >> x[row][col];
}
}

(c) Use a nested-for loop to read the values from array x and write code to display the
total, average, maximum number and minimum number.
int x[2][3] = {{14, 3, -5},{0, 46, 7}}, sum = 0, min, max;
double average = 0.00;
BACS1014 PROBLEM SOLVING AND PROGRAMMING

min = x[0][0];
max = x[0][0];

for (int row = 0; row < 2; row++) {


for (int col = 0; col < 3; col++) {
sum += x[row][col];

if (max < x[row][col])


max = x[row][col];
if (min > x[row][col])
min = x[row][col];
}
}
average = (double)sum / 6.0;

cout << "Total sum\t: " << sum << "\nAverage\t\t: " << average << "\nMaximum
number\t: " << max << "\nMinumum number\t: " << min << endl;

3. Declare a two-dimensional array called Arr2D of integer type which has 2 rows and 4
columns. Then write appropriate code segments for the following:
(a) Use for loop to obtain input from the user and store it into the Arr2D array.
for (int row = 0; row < 2; row++) {
for (int col = 0; col < 4; col++) {
cout ≪ “Enter number in row ” ≪ row + 1 ≪ “, column ” ≪ col + 1 ≪
“: ”;
cin >> Arr2D[row][col];
}
}

(b) Find and display the total of 2nd row of the Arr2D array.
int totalR2 = 0
for (int col = 0; col < 4; col++) {
totalR2 += Arr2D[1][col];
}
cout ≪ “Total of 2nd row: ” ≪ totalR2 ≪ endl;

(c) Find and display the total of last column of the Arr2D array.
int totalC4 = 0
for (int row = 0; row < 2; row++) {
totalC4 += Arr2D[row][3];
}
cout ≪ “Total of last column: ” ≪ totalC4 ≪ endl;

(d) Find the grand total and average of all the values stored in the Arr2D array.
int gTotal = 0
BACS1014 PROBLEM SOLVING AND PROGRAMMING

for (int row = 0; row < 2; row++) {


for (int col = 0; col < 4; col++) {
gTotal += Arr2D[row][col];
}
}
cout ≪ “Grand Total: ” ≪ gTotal ≪ “\nAverage: ” ≪ (double)gTotal / 8.0 ≪ endl;

4. Given the fruit price list from three different stores as shown below
Fruit Store A Store C Store T
Orange 0.80 1.00 0.69
Apple 1.20 1.50 1.80
Pear 1.50 1.55 1.29
Peach 2.00 1.99 1.80
(a) Demonstrate how to store the prices into a two-dimensional array by using C++ code.
Briefly explain your answer.
double price[4][3] = { {0.80,1.00,0.69}, {1.20,1.50,1.80}, {1.50,1.55,1.29},
{2.00,1.99,1.80} };

(b) Write a function named “get_cheap_apple” and use for loop to determine and
display the store that sells the cheapest apple.
void get_cheap_apple(double price[][3]) {
char store[3]={‘A’,’C’, ‘T’};
double cheapest = price[1][0];
char cheapest_store = store[0];

for (int col = 1; col < 3; col++) {


if (Price[1][col] < cheapest ) {
cheapest = price[1][col];
cheapest_store = store[col];
}
}
cout ≪ “Cheapest apple price is RM ” ≪ fixed ≪ setprecision(2) ≪ cheapest ≪
“ from store ” ≪ cheapest_store ≪ endl;
}

(c) Write a function named “storeC_cheapest_fruit” and use for loop to determine
and display the cheapest fruit that is sold by Store C.
void storeC_cheapest_fruit(double Price[][3]) {
double cheapest = Price[0][1];
string fruit[4]={“Orange”, “Apple”,”Pear”,”Peach”};
string cheapest_fruit = fruit[0];

for (int row = 1; row < 4; row++) {


if (Price[row][1] < cheapest ) {
cheapest = Price[row][1];
cheapest_fruit = fruit[row];
BACS1014 PROBLEM SOLVING AND PROGRAMMING

}
}
cout << fixed << setprecision(2)<< “The cheapest fruit that is sold by Store C is
” << cheapest_fruit << “ which cost RM” << cheapest << endl ;
}
(d) Write a function name “get_cheapest_fruit” and use for loop to determine the
cheapest fruit amongst all stores. Display the store name.
void get_cheapest_fruit(double Price[][3]) {
char store[3] = {‘A’, ‘C’, ‘T’};
string fruit[4]={“Orange”, “Apple”,”Pear”,”Peach”};

double cheapest_price = Price[0][0];


string cheapest_fruit = fruit[0];
char cheapest_store = store[0];

for (int row = 0; row < 4; row++) {


for (int col = 0; col < 3; col++) {
if (Price[row][col] < cheapest_price) {
cheapest_price = Price[row][col];
cheapest_fruit = fruit[row];
cheapest_store = store[col];
}
}
}
cout << fixed << setprecision(2) << "The cheapest fruit amongst all stores is "
<< cheapest_fruit << " which cost RM " << cheapest_price << “ from store ” <<
cheapest_store << endl;
}
BACS1014 PROBLEM SOLVING AND PROGRAMMING

Tutorial 9
1. The table below shows the product numbers and their respective unit prices.
Product Number Unit price
7 345.00
8 853.00
9 471.00
10 933.00
Use typedef to rename the int type to ProductNo. Then declare a variable named pNo and
initialize it with 7.
Write the switch statement to assign the unit price to a variable named uPrice according to
pNo.
typedef int ProductNo;

ProductNo pNo = 7;
double uPrice;

switch (pNo) {
case 7:
uPrice = 345.00;
break;
case 8:
uPrice = 853.00;
break;
case 9:
uPrice = 471.00;
break;
case 10:
uPrice = 933.00;
break;
}

2. What is wrong with the following pair of enumeration type declarations


enum Colors {RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET};
enum Flowers {ROSE, DAFFODIL, LILY, VIOLET, COSMOS, ORCHID};

In both Colors and Flowers have the same VIOLET value.

3. Use an enumerated type to represent the planet listed below.


Mercury, Venus, Earth, Moon, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto

enum Planet {Mercury, Venus, Earth, Moon, Mars, Jupiter, Saturn, Uranus, Neptune,
Pluto};
BACS1014 PROBLEM SOLVING AND PROGRAMMING

4. (a) Declare a structure called condo which has the following members:
 An array called location of type character with 20 elements.
 A character type variable called pattern.
 An integer type variable called area.
 A double type variable called price
Define a structure variable called alpha

struct condo {
char location[20];
char parttern;
int area;
double price;
};
condo alpha;

(b) Write C++ statements to assign the following values to the respective members of the
variable alpha:

(i) “Setapak” to location


strcpy_s(alpha.location, “Setapak”);

(ii) ‘C’ to pattern


alpha.pattern = ‘C’;

(iii) 1800 to area


alpha.area = 1800;

(iv) 550,800.00 to the price


alpha.price = 550800.00;

5. Given the following structure called house:


struct house
{
char area[20];
int squareft;
double rental;
};
BACS1014 PROBLEM SOLVING AND PROGRAMMING

Write C++ statements to perform the following tasks:

(i) Declare a variable called hse for the structure house and initialize it with values “Kita
Damansara”, 1550 and 2200.00 according to the order of the members in the structure.
house hse = {“Kita Damansara”, 1550, 2200.00};

(ii) Use the assignment operator to change the value of the rental member to 2300.00.
hse.rental = 2300.00;

(iii) Use the assignment operator to change the 2nd letter of the area member from ‘i’ to
‘o’. The new area will become “Kota Damansara”.
hse.area[1] = ‘o’;

(iv) Declare another array of structure variable called hses which contains the details of 5
houses.
house hses[5];

(v) Use a loop to change the rental of the 5 houses in the hses array to 3000.00.
for (int i = 0; i < 5; i++) {
hses[i].rental = 3000.00;
}

(vi) Assume that the details of the houses have been initialized into the hses array of
structure variable. Use an appropriate loop structure to print the details of all the 5
houses.
for (int j = 0; j < 5; j ++) {
cout ≪ “House ” ≪ j+1 ≪ “\nArea\t\t: ” ≪ hses[j].area ≪ “\nSquare Feet: ” ≪
hses[j].squareft ≪ “\nRental\t\t: ” ≪ hses[j].rental ≪ endl ≪ endl;
}

6. Given the following structure declaration:

struct date {
int day, month, year;
};

struct myfriends {
char name[20]; // name
date dob; // date of birth
};
myfriends schoolFriends;

Write C++ statements to perform the following tasks:


(a) Replace the 5th character of the member name of the structure variable schoolFriends
with the letter ‘G’.
schoolFriends.name[4] = ‘G’;
BACS1014 PROBLEM SOLVING AND PROGRAMMING

(b) Add 3 to the member year in the structure variable schoolFriends.


schoolFriends.dob.year += 3;

(c) Store the name “Peter Chan” and the day of the date of birth which is 15 into the
respective members of the schoolFriends variable.
strcpy(schoolFriends.name, “Peter Chan”);
schoolFriends.dob.day = 15;

(d) Declare another structure array variable called schoolMates which contain details of
20 schoolmates.
myfriends schoolMates[20];

(e) Use a loop to print the contents in the schoolMates array as below:
Name DOB
------- ------------
Peter Chan 20/2/1980
Celine Wong 4/12/1981
William Chang 31/8/1980
: :
: :

cout≪ “Name \t\t DOB\n”;


cout≪ “-----\t\t-----\n”;

for (int i = 0; i < 20; i++) {


cout ≪ schoolMates[i].name ≪ “\t\t” ≪ schoolMates[i].dob.day ≪ “/” ≪
schooldMates[i].dob.month ≪ “/” ≪ schoolMates[i].dob.year ≪ endl;
}
BACS1014 PROBLEM SOLVING AND PROGRAMMING

Tutorial 10
1. Before a program can read data from a file, which of the following must be true?
A. The file must exist and data to be read from it must have been previously stored in it.
B. There must be a #include <fstream> directive in the program.
C. The program must define a file stream object to associate with the file.
D. The file must be opened.
E. All the above statements must be true.

2. What error could occur if you forget to close an output file?


The output data written to the file could be lose. The information in the output buffer may
not be appended to the end of the output file and this causes the output file may be
incomplete

3. List THREE (3) advantages of using files for input and output as opposed to the standard
input and output you’ve used so far in this course.
- can store the data in the output file for future use. because data is lost after the
program ended.
- data can be saved in the output file for printing purposes.
- can process large data more efficiently by reading the data from the file rather than
keying in the data by a user using the standard input and output.

4. Perform the following tasks:


(a) Prompt the user to enter his name and age.
string name;
int age;

cout ≪ “Enter your name: ”;


cin >> name;
cout ≪ “Enter your age: ”;
cin >> age;

(b) Open a text file called myself.dat for output. Use file stream variable myfile.
ofstream myfile;
myfile.open(“myself.dat”);

(c) Write his name and age into the text file myself.dat. The sample format of the file
is as below:
Name: James | Age:18
myfile ≪ “Name: ” ≪ name ≪ “ | Age: ” ≪ age ≪ endl;

(d) Close the text file.


myfile.close;
BACS1014 PROBLEM SOLVING AND PROGRAMMING

5. Given a text file named result.dat as shown below, that stores the grades and marks
obtained by a student in a test for various subjects.

Use C++ statements to perform the following tasks:


(a) Declare the file stream variable MarkFile and use it to open the above text file
result.dat for input
ifstream MarkFile;
MarkFile.open(“result.dat”);

(b) Check if the result.dat file is opened successfully, if not, display the error message
‘File opening error” and exit the program.
if (!MarkFile) {
cout ≪ “File opening error”;
return 0;
}

(c) Read the data from the result.dat file and display the output as shown in the
following screen.

char ch;
int integer;

MarkFile >> ch >> integer


while (!MarkFile.eof()) {
cout ≪ ch ≪ integer ≪ “\t”;
MarkFile >> ch >> integer;
}
cout ≪ endl;
BACS1014 PROBLEM SOLVING AND PROGRAMMING

(d) Close the result.dat file.


MarkFile.close();
6. Write C++ program to read the following student ID and test scores from a file named
students.dat
Input file (students.dat):

Calculate the average test score and print the output shown below to a file named
compilation.dat:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
const int subjects = 5;
string student_ID;
int scores[subjects];
double avg;

ifstream inData;
inData.open(“students.dat”);
if (!inData) {
cout ≪ “Students File opening error”;
return 0;
}

ofstream outData;
outData.open(“compilation.dat”);
if (!outData) {
cout ≪ “Compilation File opening error”;
return 0;
}

int total = 0;
BACS1014 PROBLEM SOLVING AND PROGRAMMING

while (!inData.eof()){
inData >> student_ID;
outData ≪ “Student ID: ” ≪ student_ID ≪ endl;
outData ≪ “Test Scores: ”;
for (int i = 0; i < subjects; i++) {
inData >> scores[i];
outData ≪ sores[i] ≪ “ ”;
total += scores[i];
}
avg = total / subjects;
outData ≪ “Average test score: ” ≪ avg ≪ endl ≪ endl;
}

inData.close();
outData.close();

return 0;
}

You might also like