Professional Documents
Culture Documents
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
Analysis:
1. how to get total grade points
BACS1014 PROBLEM SOLVING AND PROGRAMMING
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
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;
(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
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;
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;
(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
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.
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
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;
// 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.
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
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;
(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
(b) 2 – (x + z) % 2 + 4
= 2 – (3 + 5) % 2 + 4
=2–8%2+4
=2–0+4
=6
! (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
(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
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.
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;
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;
}
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;
}
case ‘h’:
BACS1014 PROBLEM SOLVING AND PROGRAMMING
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";
}
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:
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 ++;
}
Ans:
int j = 1;
while (j <= 100)
{ cout ≪ j ≪ endl;
j++;
}
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:
The program can be compiled, but it doesn't seem to run properly. Explain what the
error is.
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
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.
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);
(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.
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;
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
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 = #
cout ≪ *ptr;
*ptr = 20;
*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
Ans: 30 30
b. int a;
int* p;
a = 2;
p = &a;
a = a + 2;
cout << *p;
c. int a;
int b;
int* p;
int* q;
a = 3;
p = &a;
q = p;
*q = *q + 5;
cout << *p;
d. int a;
int* p;
a = 4;
p = &a;
cout << (*p) / a;
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
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
What will be printed when the following C++ statements are performed?
(a) cout << strlen(a) << ", " << strlen(b) << ", " << strlen(p) << endl;
9, 4, 5
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
Car_rantal_system
calculate_total_charges
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;
int main() {
int days;
double distance;
calculate_total_charges(days, distance);
return 0;
}
return rental;
}
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;
}
Get_positive_number
Calculate_result
b. Draw the structure chart to represent the modular design of your program as
suggested in (a).
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;
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).
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.
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]
Output:
3
7
9
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”;
(c) Replace the 1st character of name based on Q4 (a) with the letter ‘p’
name[0] = ‘p’;
(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
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];
}
(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;
}
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
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.
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;
(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”},
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];
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
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];
(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];
}
}
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”};
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;
}
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) 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;
}
struct date {
int day, month, year;
};
struct myfriends {
char name[20]; // name
date dob; // date of birth
};
myfriends schoolFriends;
(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
: :
: :
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.
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.
(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;
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.
(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;
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;
}