KT14303 Lab Manual
KT14303 Lab Manual
Manual
Note:This manual is for revision purpose only. Please do not distribute it.
COMPUTER SCIENCE PROGRAM
FACULTY OF COMPUTING AND INFORMATICS
UNIVERSITI MALAYSIA SABAH
Learning Objectives/Outcomes:
Upon completion of this lab, the student should be able to:
i. write the test condition with logical, relational and equality operators
ii. implement decision statement using if, if…else, multiple if and switch statements
iii. write a statement to validate the user input based on the system requirements
Note : Please do not use any repetition statements (while, do…while and loops ) to answer this
lab exercise 3.
Practice 1: 15 minutes
Write a banking program that determines whether a bank customer qualifies for a special low-
interest rate on loan. To qualify, either ONE conditions as below must exist:-
(1) The customer’s annual salary must be at least RM 50,000
(2) The customer must have held his or her current job for at least two years.
Sample Run 1 :
LOAN QUALICATION PROGRAM
==========================
Enter your monthly salary: 5000.00
Enter the number of years at your current job: 3
You are qualifying for loan application!
Sample Run 2 :
LOAN QUALICATION PROGRAM
==========================
Enter your monthly salary: 1000.00
Enter the number of years at your current job: 1
Sorry! You are not qualifying for loan application!
1
Practice 2: 20 minutes
Write a program that reports the contents of a compressed-gas cylinder based on the first letter
of the cylinder’s color. The program input is a Character representing the observed color of the
cylinder: ‘R’ or ‘r’ for red and ‘G’ and ‘g’ for Grey and so on. Cylinder colors and associated contents
are as follows:
Your program should respond to input of a letter other than the first letters of the given colors
with the message, contents unknown.
Sample Run:
Sample Run :
Enter the Day ( e.g : 12) :31
Enter the month ( e.g : 1 for January ) :12
Enter the year ( e.g : 1993 ) :1996
*****************************THE END************************
2
Practice 1 Sample Answer :
Sample Answer:
#include <iostream>
#include <iomanip>
#define YEAR 12
#define MIN_YEAR 2
#define MIN_SALARY 5000
int main() {
float mth_salary;
short int year;
4
Practice 2 Sample Answer :
#include <iostream>
int main() {
char gas;
cout<< "Enter the first letter of the cylinder's color => ";
cin >> gas;
switch (gas){
case 'R':
case 'r':
printf("This cylinder contains ammonia.\n\n");
break;
case 'B':
case 'b':
printf("This cylinder contains carbon monoxide.\n\n");
break;
case 'G':
case 'g':
printf("This cylinder contains hydrogen.\n\n");
break;
case 'W':
case 'w':
printf("This cylinder contains oxygen.\n\n");
break;
default:
printf("Contents unknown.\n\n");
break;
return 0;
5
Practice 3 Sample Answer :
#include <iostream>
int main() {
switch (month){
case 1:
day = 31 + extra_day;
break;
case 2:
day = 28 + 31 + extra_day;
break;
case 3:
day = 31 + 28 + 31 + extra_day;
break;
case 4:
day = 30 + 31 + 28 + 31 + extra_day;
break;
case 5:
day = 31 + 30 + 31 + 28 + 31 + extra_day;
break;
case 6:
day = 30 + 31 + 30 + 31 + 28 + 31 + extra_day;
break;
case 7:
day = 31 + 30 + 31 + 30 + 31 + 28 + 31 + extra_day;
break;
case 8:
day = 31 + 31 + 30 + 31 + 30 + 31 + 28 + 31 + extra_day;
break;
case 9:
day = 30 + 31 + 31 + 30 + 31 + 30 + 31 + 28 + 31 + extra_day;
break;
case 10:
day = 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31 + 28 + 31 + extra_day;
break;
case 11:
day = 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31 + 28 + 31 + extra_day;
6
break;
case 12:
day = 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31 + 28 + 31 + extra_day;
break;
default:
cout<<"Invalid input";
break;
return 0;
7
COMPUTER SCIENCE PROGRAM
FACULTY OF COMPUTING AND INFORMATICS
UNIVERSITI MALAYSIA SABAH
Learning Objectives/Outcomes:
Upon completion of this lab, the student should be able to:
i. implement while, for do…while and nested loops statements
ii. validate user input with loop statements
iii. apply a proper loops statement to solve the given problem
Practice 1: 15 minutes
Write a C++ program that asks the user to enter a minimum value and a maximum value. Then,
the program will display the all the even numbers between the range of minimum and maximum
value.
Sample Run 1:
Enter a minimum value >> 11
Enter a maximum value >> 20
The even numbers between the 11 and 20 are:
12, 14, 16, 18
Practice 2: 20 minutes
Use a nest for loop to write a C program for the below application :
Sample Run1 :
Please enter a digit: 5
543212345
4321234
32123
212
1
Sample Run 2 :
Please enter a digit: 3
32123
212
1
1
Practice 3: 35 minutes -5 Marks
As an IT Officer in A&B Sdn Bhd, you are responsible to develop a Credit Limit Calculator, which
will determine if their customer has exceeded the credit limit on a charge account. For each
customer, the following facts are available:-
a) Account number
b) Balance at the beginning of the month
c) Total of all items charged by this customer this month
d) Total of all credits applied to this customer’s account this month
e) Type of Membership: SVIP(S), VIP(V) and Basic(B)
Your program should input each for these facts, calculate the new balance (= beginning balance
+ charges – credit), and determine if the new balance exceeds the customer’s credit limit. The
customer’s credit limit is based on their membership type as below:-
For those customers whose credit limit is exceed, the program should display the customer’s
account number, type of membership, credit limit, new balance and the message “Credit Limit”
exceeded.
Sample Run:
*****************************THE END************************
2
Practice 1 Sample Answer:
Sample Answer:
#include<iostream>
int main() {
if (min % 2 != 0) {
min = min + 1;
}
return 0;
}
4
Practice 2 Sample Answer :
#include<iostream>
int main() {
return 0;
}
int main() {
cout<<"Enter type of membership ( S for Super VIP; V for VIP; B for Basic: ";
cin>>memberhsip;
5
switch (memberhsip)
{
case 'S':
case 's':
limit=20000.00;
break;
case 'V':
case 'v':
limit = 10000.00;
break;
case 'B':
case 'b':
limit = 5000.00;
break;
default:
limit = 0.00;
break;
return 0;
}
6
COMPUTER SCIENCE PROGRAM
FACULTY OF COMPUTING AND INFORMATICS
UNIVERSITI MALAYSIA SABAH
Learning Objectives/Outcomes:
Upon completion of this lab, the student should be able to:
i. define a function prototype
ii. define function header and parameters
iii. call a function and passing arguments correctly
iv. differentiate local and global variables scope, as well as passing arguments correctly
between the functions.
v. apply top-down algorithm and divide-and-conquer approach in solving the complex
programming problems
Practice 1: 10 minutes
Write a C program that asks the user to enter a minimum value and a maximum value. Then, the program
will display the all the even numbers between the range of minimum and maximum value.
Sample Run :
Enter a minimum value >> 11
Enter a maximum value >> 20
The even numbers between the 11 and 30 are:
12, 14, 16, 18
1
Practice 2: 15 minutes
Write a program to read a word from user. The program must consist of a function called int
count_vowels(string str) that returns a count of all vowels in the string str. Vowels are
the letters a, e, i, o, and u, and their upper case variants.
Vowels Calculator
*****************
Enter a word (e.g. Excellent): Excellent
Number of 'a': 0
Number of 'e': 3
Number of 'i': 0
Number of 'o': 0
Number of 'u': 0
Total count of vowels:3
In 1954, Hans Luhn of IBM proposed an algorithm for validating credit card numbers. The algorithm is
useful to determine if a card number is entered correctly or if a credit card is scanned correctly by a
scanner. Almost all credit card numbers are generated following this validity check, commonly known as
the Luhn check or the Mod 10 check, which can be described as follows (for illustration, consider the
card number 4388576018402626):
1. Double every second digit from right to left. If doubling of a digit result in a two-digit number, add
up the two digits to get a single-digit number.
2 * 2 = 4
2 * 2 = 4
4 * 2 = 8
1 * 2 = 2
6 * 2 = 12 (1 + 2 = 3)
5 * 2 = 10 (1 + 0 = 1)
8 * 2 = 16 (1 + 6 = 7)
4 * 2 = 8
3. Add all digits in the odd places from right to left in the card number.
6 + 6 + 0 + 8 + 0 + 7 + 8 + 3 = 38
2
4. Sum the results from Step 2 and Step 3.
37 + 38 = 75
5. If the result from Step 4 is divisible by 10, the card number is valid; otherwise, it is invalid. For
example, the number 4388576018402626 is invalid, but the number 4388576018410707 is
valid.
Write a program that prompts the user to enter a credit card number as a long integer. Display whether
the number is valid or invalid.
Here are sample runs of the program:
Sample 1:
Enter a credit card number as a long integer: 4246345689049834
4246345689049834 is invalid
Sample 2:
Enter a credit card number as a long integer: 4388576018410707
4388576018410707 is valid
*****************************THE END************************
3
Sample Answer:
#include<iostream>
using namespace std;
int getMinimum(void);
int getMaximum(void);
void finEven(int, int);
int main(void) {
return 0;
}
int getMinimum(void){
int value;
cout << "Enter a minimum value >>";
cin >> value;
return value;
}
int getMaximum(void) {
int value;
cout << "Enter a maximum value >>";
cin >> value;
return value;
}
return;
}
5
Sample Answer:
#include<iostream>
using namespace std;
int count_vowels(string);
int main(void) {
string input;
int count;
cout << "Vowels Calculator";
cout << "*****************";
cout << "Enter a word (e.g. Excellent): ";
cin >> input;
count =count_vowels(input);
cout << "Total count of vowels: " << count;
return 0;
6
Practice 3 Sample Answer :
#include<iostream>
using namespace std;
int main(void) {
if (isValid(num))
cout<<num <<" is valid";
else
cout << num << " is invalid";
return result;
}
7
int sumOfOddPlace(long long digit) {
int result = 0;
while (digit != 0) {
result += (int)(digit % 10);
digit = digit / 100;
}
return result;
}
while (d != 0) {
numberOfDigits++;
d = d / 10;
}
return numberOfDigits;
}
return result;
}
8
COMPUTER SCIENCE PROGRAM
FACULTY OF COMPUTING AND INFORMATICS
UNIVERSITI MALAYSIA SABAH
Learning Objectives/Outcomes:
Upon completion of this lab, the student should be able to:
i. define and initialize array and multi-dimensional array
ii. work with common algorithm for processing the value of array
iii. write a function that receive and return arrays
iv. apply the concepts of arrays in solving the complex programming problems
Practice 1: 30 minutes
Write a program that allow users to enter up to 50 integers and find the smallest value. You
should include find_smallest function to find and return the smallest value in the array.
Sample Run:
You may enter up to 50 integers.
How many integers would you like to enter? 8
Enter your Number 1 :6
Enter your Number 2 :7
Enter your Number 3 :8
Enter your Number 4 :1011
Enter your Number 5 :2
Enter your Number 6 :20123112
Enter your Number 7 :-1
Enter your Number 8 :10
The smallest value is : -1
Practice 2: 30 minutes
Write a program that gets a series of integers input from users and find the largest value. You
should include find_largest function to find and return the largest value in the vector.
Sample Run :
How many integers would you like to enter? 10
Enter your Number 1 :10
Enter your Number 2 :21
Enter your Number 3 :233
Enter your Number 4 :-2
Enter your Number 5 :99
Enter your Number 6 :2012
Enter your Number 7 :2901
Enter your Number 8 :1011
Enter your Number 9 :2012
Enter your Number 10 :2110 1
The largest value is : 2901
Practice 3: 60 minutes -5 Marks
A barcode scanner for Universal Product Codes (UPCs) verifies the 12-digit code scanned by
comparing the code’s largest digit (called a check digit) to its own computation of the check digit
from the first 11 digits as follows:
1. Calculate the sum of the digits in the odd-numbered positions (the first, third,….. eleventh
digits) and multiply this sum by 3.
2. Calculate the sum of the digits in the even-numbered position (the second, fourth….tenth
digits) and add this to the previous result.
3. If the last digit of the result from step 2 is 0, then 0 is the check digit. Otherwise, subtract
the last digit from 10 to calculate the check digit.
4. If the check digit matches the final digit of the 12-digit UPC, the UPC is assumed correct
Write a program that prompts the user to enter the 12 digits of a barcode separated by space.
The program should store the digits in an integer array, calculate the check digit, and compare it
to the final barcode digit. If the digits match, output the barcode with the message “validated”.
If not, output the barcode with the message “error in barcode”.
Also output with labels the results from step 1 and 2 of the check-digit calculations. Note that the
“first” digit of the barcode will be store in element 0 of the array. Try your program on the
following barcodes, three of which are valid. For the first barcode, the result from step 2 is 79 ( 0
+ 9 + 0 + 8 + 4 + 0) * 3 + ( 7 + 4 + 0 + 0 + 5).
0 7 9 4 0 0 8 0 4 5 0 1
0 2 4 0 0 0 1 6 2 8 6 0
0 1 1 1 1 0 8 5 6 8 0 7
0 5 1 0 0 0 1 3 8 1 0 1
The program should included the given calculateTotal function to sum the the odd-number digits
and even-number-digits with the function signature as below:
Sample Run:
*****************************THE END***********************
2
Practice 1 Sample Answer:
Sample Answer:
#include<iostream>
int main() {
cout << "You may enter up to 50 integers. \nHow many integers would you like to
enter? ";
cin >> size;
return 0;
}
4
Practice 2 Sample Answer :
#include<iostream>
#include<vector>
int find_largest(vector<int>& );
int main() {
vector<int> v;
unsigned short int size;
int largest_value;
int value;
cout << "How many integers would you like to enter? ";
cin >> size;
largest_value = find_largest(v);
cout << "The largest value is : " << largest_value;
return 0;
}
return max;
5
Practice 3 Sample Answer :
#include <iostream>
#define MAX 12
int main(void)
{
cout<<"The sum of the digits in the odd-numbered positions: "<< sumOfOdd <<"\n";
cout << "The sum of the digits in the even-numbered positions: " << sumOfEven <<
"\n";
cout << "The sum of the digits in the even-numbered positions and odd-numbered
positions: " << sumTotal << "\n";
if (sumTotal == 0)
checkDigit = 0;
else
}
if (checkDigit == arry[11])
else
cout << "\nResult : Error in Barcode ! \n";
return (0);
}
6
void calculateTotal(unsigned int arry[], unsigned int& odd, unsigned int& even) {
unsigned short int i;
odd = 0;
even = 0;
for (i = 0; i < MAX - 1; ++i) {
if ((i + 1) % 2 == 1)
odd += arry[i];
else
even += arry[i];
}
return;
}
7
COMPUTER SCIENCE PROGRAM
FACULTY OF COMPUTING AND INFORMATICS
UNIVERSITI MALAYSIA SABAH
Learning Objectives/Outcomes:
Upon completion of this lab, the student should be able to:
i. define, initialize and use pointer
ii. work with common algorithm for processing the value of pointers
iii. write a function that receive and return pointers
iv. apply the concepts of pointers in solving the complex programming problems
Practice 1: 30 minutes
Create a program based on the following pseudocode.
1) Declare two double variables x and y and one double pointer as z.
2) The pointer z is pointed to the first variable x.
3) Prompt for two inputs x and y from user.
4) Display the pointer z memory address.
5) Display the pointer z value.
6) Sort the variables in increasing order, if it is applicable.
7) Display the pointer z value again.
8) Display the variables after sorting.
Slightly modify your program and create a function named void sort(double &x, double &y) to
perform the decrement sorting if x is smaller than y. Display the pointer value and the sorted
result after sorting.
Sample Run:
Please enter value of x and y: 12 9
Address of z: 004FFB04
Value of z: 12
New value of z after sorting: 9
Increment sorting: 9 12
New value of z after sorting: 12
Decrement sorting: 12 9
1
Practice 2: 30 minutes
Write a program that read a word from user. Then, create a function void reverse(char s[]) that
reverses a character string. For example, "Hello" becomes "olleH". Make sure pointer is used in
the reverse function.Sample Run :
Please enter a word : Hello
Hello
olleH
void instruct(void);
void dispenser(int , int* , int* , int* , int* )
Sample Run:
***************************THE END***********************
2
Practice 1 Sample Answer:
Sample Answer:
#include <iostream>
using namespace std;
int main()
{
double x, y, temp;
double* z = &x;
cout << "Please enter value of x and y: ";
cin >> x >> y;
cout << "Address of z : " << z << endl;
cout << "Value of z : " << *z << endl;
if (x > y) {
temp = x;
x = y;
y = temp;
}
cout << "New value of z after sorting: " << *z << endl;
cout << "Increment sorting : " << x << " " << y << endl;
sort(x, y);
cout << "New value of z after sorting: " << *z << endl;
cout << "Decrement sorting : " << x << " " << y;
return 0;
}
4
Practice 2 Sample Answer :
#include <iostream>
using namespace std;
/**
Reverses the values in a character array.
@param s the array
*/
void reverse(char s[])
{
char* p = s;
char* q = s;
while (*q != '\0') { q++; } // Set q to point to null terminator
q--; // Decrement q to point to last character
while (p < q)
{
char temp = *p;
*p = *q;
*q = temp;
p++;
q--;
}
}
int main()
{
char s[10];
cout << "Please enter a word : ";
cin >> s;
cout << s << endl;
reverse(s);
cout << s;
}
5
Practice 3 Sample Answer :
#include <iostream>
using namespace std;
void instruct(void);
void dispenser(int , int* , int* , int* , int* );
int main(void)
{
int withdraw, hundred, fifty, twenty, ten, error;
instruct();
do {
error = 0;
cout << "Enter withdraw Amount :";
cin >> withdraw;
if (withdraw % 10 != 0) {
error = 1;
cout << "Invalid Input !\nPlease enter a multiple of 10 dollars
\n\n";
}
} while (error);
dispenser(withdraw, &hundred, &fifty, &twenty, &ten);
cout << "Number of 100 bills : " << hundred << endl;
cout << "Number of 50 bills : " << fifty << endl;
cout << "Number of 20 bills : " << twenty << endl;
cout << "Number of 10 bills : " << ten << endl;
return 0;
}
void dispenser(int amount, int* th, int* ft, int* tw, int* tn) {
int remainder;
*th = amount / 100;
remainder = amount % 100;
*ft = remainder / 50;
remainder = remainder % 50;
*tw = remainder / 20;
remainder = remainder % 20;
*tn = remainder / 10;
remainder = remainder % 10;
}
void instruct(void) {
cout<<"ABC BANK Automatic Teller Machine ATM\n";
}
6
COMPUTER SCIENCE PROGRAM
FACULTY OF COMPUTING AND INFORMATICS
UNIVERSITI MALAYSIA SABAH
Learning Objectives/Outcomes:
Upon completion of this lab, the student should be able to:
i. read and write files
ii. convert between strings and numbers using string streams
iii. process command line arguments
iv. understand the concepts of sequential and random access
Practice 1: 30 minutes
Write a program that carries out the following tasks:
1) Open a file with the name kt14303.txt.
2) Store the message “Welcome to KT14303 Programming Principles!” in the file.
3) Close the file.
4) Open the same file again.
5) Read the message into a string variable and print it.
Sample Run:
kt14303.txt file
Console:
Welcome to KT14303 Programming Principles!
1
Practice 2: 60 minutes -5 Marks
Write a program that:
1) Prompt the user to enter a file name to save the inputs.
2) Prompt the user to enter information/statements.
3) Save the information/statements entered by a user to the file name given early.
4) Close the file.
5) Reopen the input file
6) Read all info from the file.
7) Reverse all characters from the reading.
8) Prompt the user to enter a file name to save the outputs.
9) Write the reversed results to the file.
Suppose the user specifies input.txt and output.txt when prompted for the file names,
and input.txt contains the lines
Sample Run:
Please enter a file name for input file : input
Please enter your information/statements (Enter a dot to
stop) :
Baa baa black sheep, have you any wool?
Yes sir, yes sir, three bags full!
One for the master, one for the dame,
And one for the little boy who lives down the lane.
Please enter a file name for output file : output
?loow yna uoy evah ,peehs kcalb aab aaB
!lluf sgab eerht ,ris sey ,ris seY
,emad eht rof eno ,retsam eht rof enO
enal eht nwod sevil ohw yob elttil eht rof eno dnA
2
Text file: input.txt and Output.text
***************************THE END***********************
3
Practice 1 Sample Answer:
Sample Answer:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
// Open a file with the name hello.txt.
ofstream out;
out.open("kt14303.txt");
5
Practice 2 Sample Answer :
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
ifstream input_file;
input_file.open(file_name.c_str());
cout << "Please enter a file name for output file : ";
cin >> file_name;
file_name = file_name + ".txt";
ofstream out_file;
out_file.open(file_name.c_str());
input_file.close();
out_file.close();
return 0;
}
6
COMPUTER SCIENCE PROGRAM
FACULTY OF COMPUTING AND INFORMATICS
UNIVERSITI MALAYSIA SABAH
Learning Objectives/Outcomes:
Upon completion of this lab, the student should be able to:
i. implement C++ classes.
ii. master the separation of interface and implementation.
iii. learn how to inherit and override member functions.
iv. implement constructors for derived classes.
Practice 1: 30 – 60 minutes
Create a class Rectangle. Provide a constructor to construct a rectangle with a given width and
height, member functions get_perimeter and get_area that compute the perimeter and area,
and a member function void resize(double factor) that resizes the rectangle by
multiplying the width and height by the given factor.
Practice 2: 60 minutes
Create a class Student. For the purpose of this exercise, a student has a name and a total quiz
score. Supply an appropriate constructor and functions get_name(), add_quiz(int score),
get_total_score(), and get_average_score(). To compute the latter, you also need to
store the number of quizzes that the student took.
***************************THE END***********************
1
Practice 1 Sample Answer:
Sample Answer:
A Rectangle class and a simple program to test it. I added a few extra member functions not
specified in the homework, to make the example more complete.
#include <iostream>
using namespace std;
/**
A rectangle class for calculating area and perimeter.
*/
class Rectangle
{
public:
/**
Calculates the area.
*/
double get_area() const;
/**
Calculates the perimeter.
*/
double get_perimeter() const;
/**
Returns the width.
*/
double get_width() const;
/**
Returns the length.
*/
double get_length() const;
/**
Sets the width.
@param w the target width
*/
void set_width(double w);
/**
Sets the length.
@param l the target length
*/
void set_length(double l);
/**
Changes the size of the rectangle by a factor.
@param factor the multiplier to use for scaling
*/
void resize(double factor);
Rectangle();
3
Rectangle(double w, double l);
private:
double width;
double length;
};
void Rectangle::set_width(double w)
{
width = w;
}
void Rectangle::set_length(double l)
{
length = l;
}
Rectangle::Rectangle()
{
length = 2.0;
width = 1.0;
}
Rectangle::Rectangle(double w, double l)
{
length = l;
width = w;
}
int main()
4
{
Rectangle rec1 (3.0, 4.0);
rec1.resize(2.5);
// Display information about the resized rectangle
cout << "The area is " << rec1.get_area() << endl;
cout << "The perimeter is " << rec1.get_perimeter() << endl;
return 0;
}
5
#include <iostream>
#include <string>
/**
A student who gets scores in a course.
*/
class Student
{
public:
/**
Constructs a student with no scores.
@param n the student name
*/
Student(string n);
/**
Adds a score.
@param score the score to add
*/
void add_quiz(int score);
/**
Gets the student name.
@return the name
*/
string get_name() const;
/**
Gets the total score.
@return the sum of all scores
*/
double get_total_score() const;
/**
Gets the average score.
@return the average of all scores
*/
double get_average_score() const;
private:
string name;
double total;
int count;
};
Student::Student(string n)
{
name = n;
total = 0.0;
count = 0;
}
6
}
int main()
{
Student jonathan("Jonathan Smith");
jonathan.add_quiz(10);
jonathan.add_quiz(9);
jonathan.add_quiz(8);
cout << jonathan.get_total_score() << endl;
cout << jonathan.get_average_score() << endl;
return 0;
}