The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.
Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by Wan Anisha, 2022-04-10 10:17:12

C++ eBook

C++ eBook 2022

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 6
› The subscripts must start with 0, which is why the last subscript ends with three.
› An array will start with the 0th element and end with array size -1.
› The figure also shows the arrangement of the array in a portrait orientation (a) and landscape

orientation (b).

2. One Dimensional Arrays
2.1 Array Declaration

› Like other variables, arrays also have to be declared before they are used.
› A single dimensional array is used to store multiple values in a single identifier.
› An array can be declared as: datatype arrayName[size];

• For array declarations, firstly, type any simple data type, continue with arrayName,
with any legal identifier, and the size (in square bracket).

• The size represents the number of elements the array contains.

98 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 6
› Figure below shows Illustration of a one-dimensional array declaration.

2.2 Array Initialization
› In C++ programming, we can assign or initialize values to the array. Initialization means
assigning values to an array.
› The format to write the array initialization is: datatype arrayName[size]={ elements};
› An array’s initial values are written using curly brackets { } and commas (,) to differentiate each
element in the array as shown in the following example.
› We can also initialize the values to an array without declaring the size of the array.
› The number of elements in an array can define the size of an array as shown in Example below.

› This means we can declare an array with or without size, but we must initialize the values
to it.

99 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 6
› There can also be a situation whereby we have declared the size of an array with 6 and

initialized the values for 3 elements only—the compiler will assume the next three elements
are zero as shown in example below.

2.3 Restriction in Array Operations
› Some restrictions in array operations
› Consider the following statements:
int List1[3]={5,4,3};
int List2[3];
› To copy the element in List1 into List2, the statement below are illegal:
List2=List1; //will show an error
› Thus, to copy an array into another array, use the following example:
Example:
for (int index=0;index<3;index++)
List2[index]=List1[index];
› To read data into List2, the following is also illegal:
cin>>List2;
› In the first situation, an error message will appear once we want to copy one array to another
array as shown in example below.

› We will also have a problem once we want to insert values into an array. We cannot insert or
read data to an array using the normal way.

100 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 6
› For the solution, we have to insert data to an array using the looping method as shown in

example below.

› In another situation, to retrieve a value from an array, we have to specify the index number or
the compiler will display an error message. Example 6.7 shows the solution for the situation.

2.4 Accessing Array Elements
› The for loop is commonly used to manipulate all the operations in arrays. Usually, with the
iteration or loop process, it will make the process easier because it allows us to access the
elements by referring to the subscript in the sequence.
› Besides using for loop to perform the accessing process, we also can access and initialize the
elements using the various methods as shown in example below.

101 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 6

› Besides all the methods shown, we can use other ways such as the for loop to initialize or
access arrays.

› Example below shows the general form of how to read elements into an array.

› As in a normal iteration process, we have to define the for loop argument based on the array
size.

› As usual, we have to start the iteration with zero (0), and stop the loop once we reach the
arraysize-1.

› The counter for the loop should be increased by one with each iteration.
› Example below shows a complete C++ program that creates an array and display its contents.
› This program will have an array with 10 elements that will be initialized with values and then

display them.

102 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 6

› Example below shows a complete C++ program that creates an array and displays its contents.
› The program will have two arrays, named StudentNo and Student_Marks. Both arrays will

store 3 values each.
› The program will prompt the user to insert the values for the arrays.
› Then, the program will display the contents of the arrays in table form as shown in the output.

› Example below shows a program for the flow chart in the figure beside.
› The program creates four arrays named ID[10], interest[10], balance[10] and rate[10].
› Then the program prompts the user to insert ID, balance and rate. After storing all the values

to arrays, the program calculates the balance.
103 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 6
› Finally, the program displays the values from arrays ID and balance that have been

calculated.


3. Two Dimensional Arrays
› It’s the simplest forms of multidimensional arrays.
› 2D arrays are arrays that exemplify arrays in form.
› Compared to one dimensional arrays where elements can be illustrated in a single matrix
form with one index ([ ]), 2 array are in form of two indices ([ ] [ ]) or two subscripts.
› These two indices represent the components in arrays arranged in rows and columns.
› General form of 2D array declaration:
data type arrayName [size1][size2];

104 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 6
› Below shows the illustration of memory allocation for 2D arrays:

› Below shows some example of 2d array declaration :

3.1 Accessing and Initialization of 2D Array Component
› To access and initialized 2D array are same as one -dimensional array.
› General syntax to access the element in 2D array is:
arrayName [size1][size2];

› Figure above shows simple way to access 2D array and initialized the value in it.
› The program below is an example of 2D array. The program has to create staff IDs array and

will prompt user to insert the value then print int list of the staff IDs.

105 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 6

4. Array of Characters
› In programming, a string is a one-dimensional array of characters.
› The easiest way to represent a string in an array is by using the char data type.
› The char data type will store a single character, and using a string in an array is similar to storing
a single character at each element of the array. Single quotes ('') are used to specify a single
character and double quotes ("") are used to specify a sequence of characters.
› We also have to assign the size of the array, which should be one more than the total of the
characters needed, since it needs to hold the null value \0 at the end of the array.
› General syntax of string array declaration:
char arrayName[size + 1];

106 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 6
4.1 Accessing and Initialization of String

› When we initialize a string array, we have to allocate one extra space in the memory for the
null character \0.

› This null character will terminate the array, removing any other values after it. It is not
necessary to place the null character at the end of the string because the compiler will
automatically insert it at the end of the array when it is initialized.

› General syntax of array initialization for a string:
arrayName[size + 1] = {''};

› When we initialize a string array, we must allocate one extra space in the memory for the null
character \0.

› Below show some example to assign value to an array.

› Examples below uses string or char data types for one-dimensional arrays.

› The next examples also uses string data types for one-dimensional arrays .

107 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 6
› The next examples below uses char data types for 2-dimensional arrays

5. Array operations
› In programming, we can perform a few operations to solve problems in arrays.
› These operations include summation, finding the minimum and maximum values, searching,
deleting, merging, sorting, traversing, and inserting.
› These operations are shown in Figure below.

• Traversing
› Traversing is an operation whereby each element in an array is accessed for a specific
purpose.
› Actually, in the traversal operation, we will use the values in many programs because it
is a basic operation that we have discussed before.
› The process of printing the elements, and calculations between the elements are all
examples of the traversal operation.
› Traversing is an operation whereby each element in an array is accessed for a specific
purpose.

108 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 6
› Actually, in the traversal operation, we will use the values in many programs because it

is a basic operation that we have discussed before.
› The process of printing the elements, and calculations between the elements are all

examples of the traversal operation

• Searching
› Searching means the process of finding an element in the array.
› If the element is in the array, the location or the subscript of the element will be
displayed and if the element is not available in the array, an appropriate message will
be displayed.
› There are two types of searching methods available—linear search and binary search.

5.1 Summation
› Summation is a process of adding two or more values together.
› So, in arrays, summation can be performed to find the total of the values in an array.
› Besides that, summation can also be done between any elements in an array as will be

discussed in Example below.

› Finding the sum and average of an array are shown in below example.
int sum=0;double average,sales[10];
for (int index = 0; index<10; index++)
sum=sum+sales[index];
average=sum/10;

109 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 6
› Example below shows a program segment for summation operation to find the total of an

array price[]. Here, to calculate the total of the values in an array, we have declared a variable
to accumulate the total.

› The variable should be initialized to zero before we start to accumulate the value.
› Figure below shows how the program calculates the total in the array. Summation is an

operation to find the total of the elements in an array or any two or more elements in an array.

› Example 6.25 shows a program to calculate the total marks in an array named marks[3].
› The program will also calculate the average using the total values that have been calculated

and print both the total and average.

110 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 6
5.2 Finding the maximum
› For finding the largest value in an array, we can use the maximum operation, which will

compare each element in an array to find the largest value.
› Example below shows the general form to find the largest value. We will use for loops and if

methods to check and compare each of the values in the array to find the maximum value.

› In the operation, firstly, we have to define a variable named MaxIndext and assign zero (0) to
it.

› Then, we will start to compare the values in the array using the sequence until we fulfil the
objective to find the largest value.

› Below show a full program to find the maximum value in the array.

111 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 6
› Table and memory below allocation that illustrate the process of identifying the maximum

value

5.3 Finding the minimum
› We can find the lowest value in an array using the same steps for finding the maximum value.

Here also, the operation will compare each element in an array to find the lowest value.
› Example below shows the general form to find the lowest value in an array. We will use for

loops and if methods to check and compare each of the values in the array to find the minimum
value.

› Example below shows a full program to define minimum value in an array.

112 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 6
› Figure below illustrates the process of identifying the minimum value based on Example above.
› The table shows how the values are stored as the program is executed.

6. Passing arrays to a function
› Arrays can also apply in functions in C++ program.
› An array can be passed as a parameter in a function. Example 6.30 shows the array usage in a
function.

› The program shows that a function named calculateTotal ( ) receives a parameter of type
array.

› The function will receive the values in the array, then calculate the total. It returns the total
to the main function.

› Example below shows a function that calculates the average of numbers that are keyed in by
the user. The main function will read 10 values and store them in an array named Num[10].
Then, the values in the array will be sent to the function calculateAverage() to calculate the
average and return the average value to be displayed.

113 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 6

› Example below shows a program that reads and stores the elements in an array then prints
the values in reverse order.

› A function named printListA() is created to display the elements in reverse order.
› The function receives the values in an array from the main function.

114 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS
EXERCISES

CHAPTER 1

Question 1

A toy car accelerates from 3 m/s to 5m/s in 5 s. What is its acceleration?

Formula:
v=u+at (where v=final velocity, u = Initial velocity,a = acceleration,t = time taken )

Analysis INPUT PROCESS
OUTPUT

Pseudocode

Flowchart

EXERCISE CHAPTER 1

115 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS

Question 2

The ABC telephone company gives its customers two types of packages, package A and package B. For
each package there is a basic charge and the customer is allowed to make free phone calls up to a
certain number of minutes. Any additional call will be charged 10 cents per minute. The customers are
also given a certain number of free SMS. Additional SMS will be charged 15 cents per message.

The charges of each package are as follows:

Formula:
The charge can be determined using the formula:

charge = basic charge + {total minutes - free call) x 0.10 + (total sms - free sms) x 0.15

Answer: INPUT PROCESS
Program Analysis / Specification

OUTPUT

Pseudocode

EXERCISE CHAPTER 1

116 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS

Flowchart

Question 3
Write pseudocode for the flowchart given below:

START

DECLARE double volumeC, radius;
const double PI=3.142

READ radius

CALCULATE EXERCISE CHAPTER 1
volumeC=4/3.0 *PI *pow(radius,3)

DISPLAY volume

STOP

117 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS

Pseudocode

Question 4 EXERCISE CHAPTER 1
Draw a flowchart based on the pseudocode given below:
BEGIN
DECLARE double f, a, m
GET m, a
COMPUTE f=m*a
PRINT f, m, a
END
(Hint: f=force, m=mass, a=acceleration)
Flowchart

118 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS

Question 5

When an resistors are connected in a series in an electrical circuit, the total resistance is given as
Rtotal=R1+R2+......Rn. Write a program to get the input values from the user and print out the total
resistance.

Answer:

Program Analysis / Specification

OUTPUT INPUT PROCESS

Pseudocode

Flowchart

Flowchart

EXERCISE CHAPTER 1

119 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS
EXERCISES

CHAPTER 2
Question 1: Write a C++ assignment statement for each of the following algebraic equation

Algebraic Expression Assignment Statement

G=4*pow(PI,2)*(pow(a,3)/((pow(p,2)*(x+y)))

V=(pow(a,2)/pow(b,3))*sqrt(S(S-a)))+c*d
G= 4*pow(PI,2)*pow(a,3)/(pow(p,2) * (m1+m2))

Z=5*(pow(x+y,x+3)/(2*m*n)

FV=PV*(pow(1+(INT/100),YEARS)) EXERCISE CHAPTER 2
C=2*x*y+0.25-3*a/b

120 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS EXERCISE CHAPTER 2
Question 2:
Evaluate the following expressions. Given

double x=5.5; double y=10.0; double b, z;
int n=7, m=3, j;

z=x-n/m;

b=x*y+m/n *2

j=x*m-n %m;

Question 3:
Write an appropriate declareration statement to accomplish each of the following tasks.
1. A character variable Package_code and assign charater 'L' to it.
_________________________________________________________________________________
2. A floating points variable roo1
_________________________________________________________________________________
3. A double variable name salaray and initialize RM 1125.55 it.
_________________________________________________________________________________
__________________________________________________________________________________
4. A char variable named address with length of 60.
_________________________________________________________________________________
__________________________________________________________________________________
5. A constant named gravity and assign 9.8m/s2 to it.
_________________________________________________________________________________
__________________________________________________________________________________

121 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS EXERCISE CHAPTER 2
Question 4: Writing a progam (Sequential Control Structure)

1. Write a program which input a
temperature in degrees Fahrenheit.
Then calculate the temperature in
degrees Celsius using the following
formula:
celsius = 5/9 (fahrenheit - 32)

2. Write a program which input the
radius (r) and the height (h) of a
cylinder. Then calculate the volume
of the cylinder using the following
formula:
volume = πr2 h

Question 5: Trace each of the following program and produce the output

int a = 0, b = 1, c = 2;
a--; b++; c--;
++a; --b; ++c;
a--; b++; c--;
cout<< a + 2 «endl;
cout<< --b <<endl;
cout<< c-- <<endl;

122 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS
EXERCISES

CHAPTER 3 (SELECTION CONTROL STRUCTURE)
Question 1
Writing a boolean expression

Expression Result
108 <= 12 * 12
bool Q1=true, Q2=true, Q3=false;
CQ1 || Q2 && Q3
int a=6, b=3, c=5;
i. a!=6||b<3

ii. b>=4 && c==5
iii. 5<=a && b>3 || c!=5

Question 2

Write an appropriate if. .else statements for each of the following:

If number is negative,
add the number to
NEGT, otherwise add the
number to PSTF.

If mark is more than 10, EXERCISE CHAPTER 3
print a message "Very
Good", otherwise print a
message "Good"

123 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS EXERCISE CHAPTER 3
Question 3
Pop-In Sdn Bhd runs a cybercafe and charge as follows:
A 10% discount will be given to the customer who spends more than 3 consecutive hours at the
cybercafe. Write a C++ program segment that calculate the actual charge for a customer based on
the number of hours spent.

124 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS EXERCISE CHAPTER 3
Question 4
The National Earthquake Center has asked you to write a program implementing the following
decision table to characterize an earthquake based on its Richter scale number.

The program accepts the Richter scale value and determines the earthquake characterization from
the above table.

0

125 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS EXERCISE CHAPTER 3
Question 5
Tracethe output for the progam given:

int p=10, q=5,r=10;
if (p>q && p<=r)

p = p + 1;
else

r = r + 1;
cout<<p<<" "<<r<<endl;

int number = 5;
if(number>2 && number<= 5)

cout<<"first"<<endl;
if (number < 7 && 3 > number)

cout<< "second"<<endl;
if(number<1||number>=number)

cout<< "third"<<endl;

126 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS

EXERCISES

CHAPTER 4 (REPETITION CONTROL STRUCTURE)

Question 1

int pass = 0, a = 10,score;
while (a >= 1)
{

cin>>score;
if (score < 50)

pass = pass + score;
a = a - 1;

}

What output is produced if the value of x is 3
and y is 4?

What output is produced if the value x is:
7, 10, 4, -1, 6, 8

l; EXERCISE CHAPTER 4

127 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS EXERCISE CHAPTER 4
Question 2
Write a C++ program based on the following pseudocode:

Set total to zero
Set grade counter to one
While grade counter is less than or equal to ten

Input the next grade
Add the grade into the total
Add one to the grade counter
Set the average to the total divided by ten
Print the average

128 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS EXERCISE CHAPTER 4
Question 3
The factorial of non-negative integer n is written as n\ and is defined as follows.
Write a C++ program that reads a non-negative integer value, computes the factorial and prints the
result

129 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS EXERCISE CHAPTER 4
Question 4
Write a program that prompts the user to enter a series of numbers, ends with zero. The program
has to do the following calculation and print the results.
• Count the number of data entered by the user
• Calculate the total of all numbers
• Calculate the average of all numbers

Question 5
Write a complete C++ program that prompts the user to enter an integer, checks whether the integer
is an odd number and divisible by 7, and prints an appropriate message.
NOTE: An integer is divisible by 7 when it divides perfectly by 7 and leaves no remainder.

130 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS EXERCISE CHAPTER 4
Question 6
Write a C++ program segment that allows user to enter a score. If the score is less than 0 or greater
than 100, the program should print an appropriate message informing the user that an invalid score
has been entered, else, calculate the total and average of the scores. When a score of 999 is entered,
the program should exit from the loop and display the total and average scores.

131 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS EXERCISE CHAPTER 5
EXERCISES

CHAPTER 5 (FUNCTIONS)
Question 1: Trace the output for the progam given

void fl(int&, int, int&);
void main()
{

int a, b, c;
a = 10; b = 20; c = 30;
fl (a, b, c) ;
cout << a << ' ' << b <<' ' ;
}
void fl(int& x, int y, int& z)
{

cout << x << ' '<< y << ' ';
x = 1;
y = 2;
z = 3;
}

132 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS EXERCISE CHAPTER 5

Question 2
Write the definition for each of the following C++ functions:
a) Function CalculateSum() receives two integer numbers. Calculate and return the sum of two

numbers

133 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS EXERCISE CHAPTER 5
b) Function CalculateDivision() receives two integer numbers. Calculate and return the product of

two numbers.

Question 3
Write the definition for each of the following C++ functions:
(NOTE: 1 liter of petrol: RM2.70, 1 liter of diesel: RM2.58, 1 liter of gas : RM0.68
a) Function CalculateGas ( ) receives the amount in liters

134 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS EXERCISE CHAPTER 5
b) Function CalculatePetrol ( ) receives the amount in liters. Calculate and return the total cost of

petrol.

c) Function CalculateDiesel ( ) receives the amount in liters. Calculate and return the total cost of
diesel.

135 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS EXERCISE CHAPTER 6
EXERCISES

CHAPTER 6 (ARRAY)
Question 1
Trace the output for the progam given

136 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS EXERCISE CHAPTER 6

Question 2
Write the code segments for the following tasks
137 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS EXERCISE CHAPTER 6

Write the code segments for the following tasks:
i) To print grades array in reversal order.
ii) To calculate the total of milesPerGallon.

138 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS

Question 3

EXERCISE CHAPTER 6

139 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS EXERCISE CHAPTER 6
Question 4
Write a program that reads TEN (10) integers and störe them into an array. Determine whether there
are any duplicates in the array's elements. Display the message "Duplicate found" if there is at least
one duplicate integer and "Duplicate not found" if all the integers are unique.

140 | P a g e

LAB EXERCISES

Lab # 1 (OUTPUT STATEMENT)

1. *
*****

*********
*************

2. C
CC CC
CC CC

CCCCCCCCC
CC CC
CC CC
CC CC

3.

4.

(_)

(_)

||

@@@@@@@@@@@@@ ^^^^^^

@@ (^)

@@@@@@@@@@@@@@@@@ ()

@@ (^ )

@@ (^ ^ )

@ @@@@ @ ||

@ @@ @ ||

@ @@ @ ||

@@@@@@@@@@@@@@@@ ----

_____________

/ | | \\ LAB EXERCISES

_______ /________________\\_____

( __ ()

(_______( )____________( )_______()

() ()

141 | P a g e

3. LAB EXERCISES
4.
7.

142 | P a g e

LAB EXERCISES LAB EXERCISES
Lab # 2 (SEQUENTIAL CONTROL STRUCTURE)
1. Write a C++ program to calculate cone given the formula as 1/3 pi r 2 h.

2. Write a program that asks the user to enter a 2 integer numbers. Calculate the sum, minus,
division, multiplication and average of the 2 numbers.

3. Write a program that requires the user to enter the time travelled for a vehicle in minutes and
fuel usage in liter. Given the average speed of the vehicle is 75km/h. The program will calculate
the distance travelled in kilometer and the fuel consumption in liter per kilometer used by the
vehicle.
Formula:
Distance Travelled (km) = Average Speed * (Time travelled/60)
Fuel Consumption (liter/km) = Fuel Usage / Distance Travelled

4. Write a program that will calculate salary of a person based on total of working hours in a week
and working salary for an hour. Output of the program should be on total of working hours in
a week, working salary for an hour, total salary for a week and final salary (after 5% EPF
deduction).

143 | P a g e

LAB EXERCISES
Lab #3 (SEQUENTIAL CONTROL STRUCTURE-FORMATTING OUTPUT)

1. Write a C++ program that input staff name (string), staff id (string) and salary (double).
Calculate the bonus and total, then print the values as follow:

NAME:...............Siti Fatimah
STAFFID.............******A123
BASIC SALARY(RM)....***1850.50
BONUS(RM)...........****(20% of basic salary)
TOTAL(RM)...........***basic salary + bonus

2. Write a program on a restaurant billing system. The program should ask the user to enter the
cashiers name and menu together with the price for each menu. Then, calculate the total price
and print the receipt as below:

**Use field width for the output arrangement

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

RESTORAN ABC TOMYAM

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

Cashier: AR RAMLI

Menu Harga

---- -----

Nasi Putih RM 1.00

Tomyam Campur RM 4.50

Kailan Ikan Masin RM 3.00

Air Sirap RM 1.50

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Total RM 10.00

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

3. ATUhSaBnckomypoauny.isPclhaeragsineg 7c%oimnteereasgtapierny.ear for a total amount of loan. The monthly payment
will be paid for a certain period of time. You are required to calculate the monthly payment
based on the following information:
Input – name, loan amount, time period

Output – monthly payment

4. Write a user-friendly program to calculate the circumference and the area of a circle from a LAB EXERCISES
user’s entry of its radius. Generate the tabular display showing the circle’s radius, circumference
and area.

(Note: circumference of a circle is calculated using the equation 2rand the area of a circle is

calculated using the equation r 2)

144 | P a g e

LAB EXERCISES LAB EXERCISES
Lab #4 (SELECTION CONTROL STRUCTURE)
1. Write a C++ program to calculate Body Mass Index (BMI) for adult by using the following formula:

BMI = Weight (kg) / (Height (m) x Height (m))
• If Your BMI is Less than 18.5, display "You are underweight"
• If Your BMI is 18.5 to less than 25, display " Your weight is desirable"
• If Your BMI is 25 to less than 30, display "You are overweight"
• If Your BMI is 30 or more, display "You are obese"
• Else display invalid data
2. Write a program that asks the user to enter 2 integer numbers and an operation (+. -, *, /).
Provide some calculations based on the operation chosen. Then, based on the calculation, the
program will identify the results whether it is an odd or even number.
3. The following table shows the average speed per hour for two types of vehicles:

Write a program that requires the user to enter the vehicle code, time travelled for a vehicle
in minutes and fuel usage in liter. The program will calculate the distance travelled in kilometer
and the fuel consumption in liter per kilometer used by the vehicle.
Formula:
Distance Travelled (km) = Average Speed * (Time travelled/60)
Fuel Consumption (liter/km) = Fuel Usage / Distance Travelled
4. Each disk drive in a shipment of these devices is stamped with a code from 1 to 4, which
indicates a drive manufacturer as follows:

The program will accept the code number as input and based on the value entered, displays
the correct disk drive manufacturer. The program should be able to display an error
message if the data input is not in the range stated in the table.

145 | P a g e

5. Write a program to display message for the tank water level according to the given information
below:

Amount (litre) Message
0-149 very little amount

150-500 little amount
501 – 1000 medium amount
1001 – 1500
tank is full

6. An employee of an electronic company is paid based on the total working hours. Each
employee will be paid based on a certain rate:

Total hours Rate per hour

Less than 160 hours RM 5.00

160 hours to 170 hours RM 5.50

More than 170 hours RM 5.75

Calculate monthly salary for the employee and display the output.

7. Write a program which as the user to enter the printer type and display a message according to
the selected printer as below

Printer type Message Print type Message
1 Canon printer
1 Bold print
2 Italic print

Dot matrix print

2 HP Printer 1 Enlarged print

2 Condensed print

Dot matrix print

Printer not
available

LAB EXERCISES

146 | P a g e

LAB EXERCISES
Lab #5 (REPETITION CONTROL STRUCTURE)
1. Write a C++ program which input the basic salary of an employee and scheme code. The program

will then calculate EPF and SOCSO according to the scheme of the employee.

The program will be repeated until request to stop.

2. Write a program that accepts an integer value from the user. The program will display a list of
square root numbers based on the integer value entered. Refer to the following example.
Please enter a number: 5
List of square root numbers are:

3. Any Maybank’s customer will be able to enjoy 14% dividen at the end of every year. If a customer
has RM5050.10 in his Maybank account in January 2005, how much will he have after 15 years?
Write a program that updates his account. Use for loop.

4. Write a program to print out a conversion table of temperatures. (Formula: C=5/9(F-32) )
Enter the minimum (whole number) temperature you want in the table, in Fahrenheit: 0
Enter the maximum temperature you want in the table: 100
Enter the temperature difference you want between table entries: 20

Tempertature conversion table from 0 Fahrenheit
to 100 Fahrenheit, in steps of 20 Fahrenheit:

Fahrenheit Celsius LAB EXERCISES
0 -17.78
20 -6.67
40 4.44
60 15.56
80 26.67
100 37.78

147 | P a g e


Click to View FlipBook Version