Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Compiled by:
MAILYNE V. BACONGCO, CpE
SKSU Vision
A trailblazer in art, science and technology in the region.
SKSU Mission
The University shall primarily provide advanced instruction and professional training in
science and technology, agriculture, fisheries, education and other relevant fields of
study. It shall also undertake and extension services, and provide progressive
leadership in its areas of specialization.
TABLE OF CONTENT
Topic
Part I: Assembly Language
Lesson 1: Binary and Hexadecimal Integers
Introduction
Learning Outcome
Activating Prior Knowledge
Activity 1: Fill the Box
Activity 2: Complete Me
Setting the Context
Activity 3: Conversion: Binary to Decimal
Activity 4: Conversion: Decimal to Binary
Activity 5: Conversion: Binary to Hexadecimal
Activity 6: Conversion: Hexadecimal to Binary
Activity 7: Conversion: Hexadecimal to Decimal
Comprehension Check
Activity 8: Problem Solving
Practice and Application
Activity 9: Do it yourself
Closure
Activity 10: Individual Work
Lesson 2: Signed Integer
Introduction
Learning Outcome
Activating Prior Knowledge
Activity 1: My negative side
Setting the Context
Activity 2: 8-bit binary notation
Activity 3: Find my Match
Activity 4: Valid or Invalid
Activity 5: Positive or Negative
Activity 6: 16-bit hexadecimal
Practice and Application
Activity 7: Do it yourself
Closure
Activity 8: Individual Work
Lesson 3: Floating point Binary
Introduction
Learning Outcome
Activating Prior Knowledge
Activity 1: Conversion: Fraction to Decimal
Setting the Context
Activity 2: Base 10 Fraction and Decimal
2
Activity 7: Interpretation
Lesson 7: A First Look at a C++ Program
Introduction
Learning Outcome
Activating Prior Knowledge
Activity 1: True or False
Setting the Context
Activity 2: Identification
Activity 3: True or False
Activity 4: Always, Sometimes, or Never
Activity 5: Fill in the Blank
Activity 6: Encircle Me
Activity 7: True or False
Practice and Application
Activity 8: Do it yourself
Lesson 8: Variables and Constants
Introduction
Learning Outcome
Activating Prior Knowledge
Activity 1: Encircle Me
Setting the Context
Activity 2: True or False
Practice and Application
Activity 3: Do it yourself
Lesson 9: Arithmetic Expressions
Introduction
Learning Outcome
Activating Prior Knowledge
Activity 1: Find the Output
Setting the Context
Activity 2: Fix the Bug
Activity 3: True or False
Activity 4: Fill in the Blank
Practice and Application
Activity 5: Write a program
Lesson 10: Arrays, apvector and apmatrix Classes
Introduction
Learning Outcome
Activating Prior Knowledge
Activity 1: True or False
Setting the Context
Activity 2: Valid or Invalid
Practice and Application
Activity 3: Test my Program
Activity 4: Fix the Bug
4
Part I
Lesson
Learning Outcomes
At the end of the lesson the students can solved the following types of
problems:
a. Identify positional values for an 8-bit binary numbers;
b. Write the equivalent binary and hexadecimal representation of decimal
number;
c. Convert decimal to binary, binary to decimal, hexadecimal to decimal,
binary to hexadecimal, and hexadecimal to binary; and
d. Solved any number system to its desired base.
Bit Value
Position value as
a power of base 2
Bit number
1
128
0
6
Complete Me
Directions: Complete the table by writing the equivalent binary and hexadecimal
representation of decimal number. Decimal number 2 was already done for
you.
Decimal Number
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Binary Representation
Hexadecimal Representation
0010
6. 12 =
2. 7 =
7. 15 =
3. 5 =
8. 16 =
4. 8 =
9. 20 =
5. 9 =
10. 27 =
6. 00011100 =
2. 00001111 =
7. 00110000 =
3. 00010000 =
8. 00100111 =
4. 00010110 =
9. 01000000 =
5. 00001011 =
10. 01100011 =
6. 00011100 =
2. 00001111 =
7. 00110000 =
3. 00010000 =
8. 00100111 =
4. 00010110 =
9. 01001000 =
5. 00001011 =
10. 01100011 =
6. 001C =
2. 000Fh =
7. 0030h =
3. 0010h =
8. 0027h =
4. 0016h =
9. 0048h =
8
5. 000Bh =
10. 0063h =
6. 041Ch =
2. 002Fh =
7. 0B30h =
3. 0110h =
8. 06DFh =
4. 0216h =
9. 1AB6h =
5. 004Bh =
10. 0A63h =
Comprehension Check
Problem Solving
Directions: Convert the following number system to its desired base. Number 1 is
provided for you. Write your Solution and answer in the space provided.
1. 37410
to base2
Solution:
374/2 = 0
187/2 = 1
93/2 = 1
44/2 = 0
23/2 = 1
11/2 = 1
5/2 = 1
2/2 = 0
=1
Answer: 1011101102
2. 37410 to base8
Solution:
3. 75348 to base2
Solution:
4. CAFE16 to base10
Solution:
10
5. 25368 to base16
Solution:
DO it yourself
Directions:
1. Convert the following binary numbers to their decimal representation:
a. 11 =
c. 111011 =
b. 1101 =
d. 0101 =
c. CEF =
b. A1 =
d. BA9 =
c. 42 =
b. 4000 =
d. 4095 =
c. 10110 01101 =
d. 11111 01011 =
5. Do the hexadecimal arithmetic:
a. 82CD + 1982 =
c. FB28 3254 =
b. E2C + A31 =
d. E2C A31 =
d. 5FCA5243
+AE223464
b. E3BA265F
+ E045B9A9
e. 80000000
+7FFFFFFF
a. E9B20F5D
+FE605C8D
f. 6D4AFBC0
+F89ABCDE
Closure
Individual Work
Directions:
1.
2.
3.
4.
12
Lesson
SIGNED INTEGER
Introduction
In mathematics, the additive inverse of a number n is the value, when added to n,
produces zero. Programs often include both subtraction and addition operations, but
internally, the CPU really only performs addition. To get around this restriction, the
computer uses the additive inverse. When subtracting A-B, the CPU instead performs A+
(-B).
Learning Outcome
At the end of the lesson the students can solved the following types of
problems:
a. write the equivalent negative binary numbers of positive numbers;
b. write signed decimal integers in 8-bit binary notation;
c. identify the valid 16-bit signed decimal integers; and
d. perform subtraction of unsigned decimal number.
My negative side
Directions: Write the equivalent negative binary number of the following positive number.
Number 1 was already done for you.
1.
Number +53
Reverse the bits
Add 1
Number -53
00110101
11001010
1
11001011
Number +36
Reverse the bits
Add 1
Number -36
00110101
11001010
1
2.
13
3.
Number +75
Reverse the bits
Add 1
Number -75
00110101
11001010
1
Number +48
Reverse the bits
Add 1
Number -48
00110101
11001010
1
Number +57
Reverse the bits
Add 1
Number -57
00110101
11001010
1
4.
5.
5. +15
11111110
2. -7
6. -1
3. -128
7. -56
4. -16
8. +127
14
Find my match
Directions: Match column A to column B by drawing a line connecting to its equivalent
decimal. Number 1 was already done for you provided.
Column A
Column B
1.
2.
3.
4.
5.
6.
7.
8.
1. +15
2. -16
3. +85
4. -4
5. -1
6. -127
7. -128
8. -81
11111111
11110000
10000000
10000001
00001111
10101111
11111100
01010101
Valid or Invalid
Directions: Which of the following integers are valid 16-bit signed decimal integers?
Write your answer in the box provided.
(Indicate V=valid, I=invalid)
1. +32469 =
4. +32785 =
2. +32767 =
5. -32785 =
3. -32768 =
6. +65535 =
15
Positive or Negative
Directions: Indicate the sign of each of the following 16-bit hexadecimal integers:
Write your answer in the box provided.
(indicate P=positive, N=negative)
1. 7FB9h =
2. 8123h =
3. 0D000h =
4. 649Fh =
16-bit Hexadecimal
Directions: Write each of the following signed decimal integers as a 16-bit hexadecimal
value. Write your answer in the box provided.
1. -42
5. -32768
2. -127
6. -1
3. -4096
7. -8193
4. -16
8. -256
15
Do it yourself
Directions: Perform the subtraction with the following unsigned decimal numbers by
taking the 10s complement of the subtrahend. Number 1 was already done
for you.
1. 5250 1321 (4 digit)
Solution:
(M>=N)
First take 10s complement on 1321:
10^4 1321 = 9999 1321 + 1 = 8679
Then sum the numbers together:
M = 5250
10s complement of N = +8679
Sum = 13929
Discard end carry
= -10000
Answer = 3929
16
3. 20 40 (2 digits)
Solution:
17
Closure
Individual Work
Directions: Perform the subtraction with the following unsigned binary numbers by
taking the 2s complement of the subtrahend. Write your answer in the box
provided.
1. 11010 10000 (5 digits)
Solution:
18
Lesson
FLOATING-POINT BINARY
Introduction
Floating point numbers are numbers that contain a fractional part i.e. they contain
a decimal point with numbers after it. They are called floating point because the point can
float or move when the number is expressed using scientific notation.
Learning Outcome
At the end of the lesson the students can solved the following types of
problems:
a. convert fractions to decimal base;
b. write the equivalent base10 fraction and base10 decimal of binary
floating-point numbers;
c. write the actual binary bits used for an 8-bit exponent in the IEEE Short
Real format; and
d. perform floating point addition on the following pairs of values, which
are written in scientific notation.
2. 0.21438
19
3. 101.1012
4. 0.00012
5. 101010.11112
Base 10 Fraction
1 5/8
Base 10 Decimal
1.625
20
Exponent (E)
2
5
0
-10
128
-1
Binary Representation
10000001
Normalized As
1.000011
Exponent
4
21
Do it yourself
Directions:
1. Perform floating point addition on the following pairs of values, which are written
in scientific notation. Assume that there are only 5 places of accuracy in the
mantissa. Show your solution.
a. 7. 3892 * 1017
+1.8901 * 1019
c.
7. 3892 * 1014
+1.8901 * 1027
2. Perform Floating point multiplication on the following pairs of values: Show your
soluition.
a. 7. 3892 * 1014
*1.8901 * 1027
b.
3.6000 * 1014
* 5.0000 * 1017
22
Closure
Raw bits
Unsigned
Signmagnitude
Excess-8
2s
complement
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
23
Lesson
Learning Outcome
At the end of the lesson the students can solved the following types of
problems:
a. identify the validity of MOV instruction;
b. identify the validity of unsigned operands; and
c. distinguish carry or no carry, zero or not zero flags.
Directions: Indicate whether or not each of the following MOV instructions is valid:
(notate: V = valid, I = invalid)
1. mov ax, bx =
2. mov dx, bl =
4. mov si,di =
5. mov ds, ax =
6. mov ds,es =
7. mov al, dh =
8. mov ax,dh =
9. mov ip,ax =
Valid or Invalid
Directions: Indicate whether or not each of the following instruction is valid.
(notate: V = valid, I = invalid) Assume that all operands are unsigned.
Instruction
1. add ax, bx
2. add dx, bl
3. add ecx, dx
4. sub si, di
5. add bx, 90000
6. sub ds, 1
7. dec ip
8. dec edx
9. add edx, 1000h
10. sub ah, 126h
Valid or Invalid
Carry or No carry
Directions: What will be the value of the Carry flag after each of the following instruction
sequences has executed?
(notate: CY = carry, NC = no carry)
1. mov ax, 0FFFFh
add ax, 1
2. mov bh, 2
sub bh, 2
3. mov dx, 0
dec dx
4. mov
al, 0DFh
add
al, 32h
5. mov
si, 0B9F6h
sub
25
si, 9874h
6. mov
cx, 695Fh
sub
cx, A218h
4. mov
al, 0DFh
add
al, 32h
2. mov bh, 2
sub bh, 2
5. mov
si , 0B9F6h
sub
si,9874h
3. mov dx, 0
dec dx
6. mov
cx, 695Fh
add
cx,96A1h
Positive or Negative
Directions: What will be the value of the sign flag after each of the following instruction
sequences has executed?
(notate: PL = positive, NG = negative)
1. mov ax, 0FFFFh
subax, 1
2. mov bh, 2
sub bh, 3
4. mov
ax, 7FFEh
add
ax, 22h
5. mov
si, 0B9F6h
26
sub
si, 9874h
3. mov dx, 0
dec dx
6. mov
cx, 8000h
add
cx, A69Fh
cx,96A1h
27
Do it yourself
Directions: Create a program that ask two digits from the user, stores the digits in the
EAX and EBX register respectively, adds the values, stores the result in a
memory location res and finally displays the result. Write your code in the box
provided. Use extra sheet of paper if the code doesnt fit in the box.
28
Lesson
Learning Outcome
At the end of the lesson the students can solved the following types of
problems:
a. identify the validity of MOV instruction;
b. write the hexadecimal value of MOV instructions; and
c. create programs that can store data in the memory.
Valid or Invalid
Directions: Indicate whether or not each of the following MOV instructions is valid:
(notate: V = valid, I = invalid)
Use the following data declarations for Question -4. Assume that the offset of byteVal is
00000000h, and that all code runs in Protected mode.
.data
byteVal
wordVal
dwordVal
aString
1. Mov
BYTE 1,2,3,4
WORD 1000h, 20000h, 3000h, 4000h
DWORD 12345678h, 34567890h
BYTE ABCDEFG, 0
4. mov
29
ax, byteVal
si, aString
2. Mov
dx, wordVal
5. mov
esi, offset
aString
6. mov
al, byteVal
3. Mov
ecx, dwordVal
Valid or Invalid
Directions: Indicate whether or not each of the following MOV instructions is valid:
(notate: V = valid, I = invalid)
1. mov
eax, offset
byteVal
4. mov
si, dwordVal
2. mov
dx, wordVal+2
5. mov
esi, offset
aString+2
3. mov
ecx, offset
dwordVal
6. mov
al, offset
byteVal+1
Hexadecimal Value
Directions: Indicate the hexadecimal value moved to the destination operand by each of
the following MOV instructions: (If any instruction is invalid, indicate I as the
answer.)
1. mov
ax, offset
byteVal
4. mov
esi, offset
wordVal
2. mov
dx, wordVal
5. mov
esi, offset
aString
30
3. mov
ecx, dwordVal
6. mov
al, aString+2
Hexadecimal Value
Directions: Indicate the hexadecimal value moved to the destination operand by each of
the following MOV instructions: (If any instruction is invalid, indicate I as the
answer.)
1. mov
eax, offset
byteVal+2
4. mov
esi, offset
wordVal+4
2. mov
dx, wordVal+4
5. mov
esi, offset
aString-1
3. mov
ecx, dwordVal+4
Hexadecimal Value
Directions: Indicate the hexadecimal value moved to the destination operand by each of
the following MOV instructions: (If any instruction is invalid, indicate I as the
answer.)
Use the following data declarations for Questions 5-6. Assume that the offset of byteVal
is 0000:
31
.data
byteVal
wordVal
dwordVal
dwordValSiz
ptrByte
ptrWord
BYTE 3 DUP(0FFh),2,"XY"
WORD 2 DUP(6),2
DWORD 8,7,6,5
WORD ($ - dwordVal)
DWORD byteVal
DWORD wordVal
1. mov
eax, offset
wordVal
4. mov
si, dwordValSiz
2. mov
dx, wordVal+4
5. mov
al, byteVal+4
3. mov
ecx, dwordVal+4
Hexadecimal Value
Directions: Indicate the hexadecimal value moved to the destination operand by each of
the following MOV instructions: (If any instruction is invalid, indicate I as the
answer.)
1. mov
ax, dwordVal+2
5. mov
esi, ptrWord
2. mov
dx, wordVal-2
6. mov
edi, offset
dwordVal+2
3. mov
eax, ptrByte
32
Do it yourself
Directions: Create a program that store name Zara Ali in the data section of the memory.
Then changes its value to another name Nuha Ali programmatically and
displays both the names. Write your code in box provided.
33
Part II
Lesson
Learning Outcome
At the end of the lesson the students can solved the following types of
problems:
a. identify the software and hardware part of a computer system;
b. write the equivalent hex and decimal number of binary number system;
c. write the ASCII codes of the characters in decimal, hex and binary; and
d. Interpret the hex dump of an ASCII data file.
H or S
Directions: Are the following entities or devices part of a computer systems hardware
(H) or software (S). Write your answer in the blank provided.
1. Operating system
2. CPU
3. Compiler
4. Program editor
5. IDE
6. GUI (Graphical User Interface)
7. Assembler
8. Bus
9. RAM
10. ROM
11. File
12. Modem
___________
___________
___________
___________
___________
___________
___________
___________
___________
___________
___________
___________
34
Guess Me
Directions: Answer what is ask. Write your answer in the space provided.
1. What is the maximum number of different codes or numbers that can be
represented in 3 bits? __________
8 bits? ____________
2. An experiment consist of tossing a coin 10 times and its outcome is a sequence of
heads and tails. How many possible outcomes are there? _____________
3. A 12 bit A/D converter digitizes amplitudes of an analog signal into 12-bit numbers.
How many different digitized amplitude values are possible?
________________________________________
4. 16-bit addresses can directly address 64KB of memory. How much memory (in
MB) is directly addressable with 32-bit addresses? ______________________
5. If a GIGTEL microprocessor can directly address 1024 GB of memory, what
should the width of the address bus be? _______________________________
1.
2.
3.
4.
5.
6.
7.
Binary
00011100
decimal
28
hex
1C
00000011
00001111
00101111
10000001
11000001
00001011
11110101
______________
______________
______________
______________
______________
______________
______________
______________
______________
______________
______________
______________
______________
______________
35
1.
2.
3.
4.
5.
Binary
00000011 00001111
decimal
3*256 +15 = 783
hex
030F
00000001 1100001111
00001111 00001011
10000000 00000000
11111111 00000000
10000001 10000001
______________
______________
______________
______________
______________
______________
______________
______________
______________
______________
1.
2.
3.
4.
A
a
Q
q
Decimal
_________
_________
_________
_________
hex
__________
__________
__________
__________
binary
_____________
_____________
_____________
_____________
Solve for x
Directions: Solve for x, where x is a (decimal) number. A character in single quotes
represents the ASCII code for that character:
1. 5 x = O
2. G + x = g
3. x + j = [
x = _____________
x = _____________
x = _____________
36
Interpretation
Directions: Interpret the following hex dump of an ASCII data file:
1.
2.
3.
4.
5.
6.
7.
8.
9.
45 4E 47 4C 49 53 48 2D-49 54 41 4C 49 41 4E 20
44 49 43 54 49 4F 4E 41-52 59 0D 0A 77 61 6E 74
20 20 20 20 76 6F 6C 65-72 65 0D 0A 61 20 20 20
20 20 20 20 75 6E 0D 0A-49 20 20 20 20 20 20 20
69 6F 0D 0A 70 72 6F 67-72 61 6D 20 70 72 6F 67
72 61 6D 6D 61 0D 0A 74-68 69 73 20 20 20 20 71
75 65 73 74 6F 0D 0A 74-6F 64 61 79 20 20 20 6F
67 67 69 0D 0A 6C 6F 76-65 20 20 20 20 61 6D 61
72 65 0D 0A
______________
______________
______________
______________
______________
______________
______________
______________
______________
37
Lesson
Learning Outcome
At the end of the lesson the students can solved the following types of
problems:
a. identify the statements required in C++ syntax or optional C++ style;
b. identify the valid names of a C++ programs; and
c. construct and restrict C++ program.
True or False
Directions: Mark True or False. Refer to the following program:
#include <iostream.h>
#include apstring.h
int main ()
{
apstring firstName;
cout <<Please enter your first name:;
cin >> firstname;
cout <<firstname
<<,
38
<<
<< Congratulations on your first program!
<<endl;
return 0;
}
1.
2.
3.
4.
5.
6.
________
________
________
________
________
________
________
Identification
Directions: Identify the following statements as referring to required C++ syntax or
optional C++ style:
1.
2.
3.
4.
5.
6.
7.
8.
________________
________________
________________
________________
________________
________________
________________
________________
True or False
Directions: Mark True or False.
1.
2.
3.
4.
______
______
______
______
39
______
______
______
Encircle Me
Directions: Circle all names below that can be used as valid names in a C++ program
without generating a syntax error (even though they may be stylistically awful):
1. 7seas
2. _get_3
3. cin.get
4. Cout
5. long^
6. INT
7. cout_
8. _0
40
True or False
Directions: Mark True or False.
1. cin is called the stream extraction operator. ___________
2. In the statement:
ifstream inFile (DICT.DAT);
ifstream is the standard name of the file output class and inFile is a name chosen
by the programmer._____________
3. The #include <iostream.h> directive must be include in any program that uses
cout or cin. ______________.
4. Every program sends its output to cout. __________
Do it yourself
Directions:
1. What is the output of the following code?
cout<<Fun
<<day\n;
a. syntax error
b. Fun day\n
c. Fun
day
d. Funday
e. Depends
2. The following program converts temperatures from Celsius to Fahrenheit:
int main ()
{
double degC, degF;
cout<<Please enter degrees Celcius: ;
cin>>degC;
degF = 32 + 9 / 5 * degC;
cout <<degC << C is << degF << F\n;
return 0;
}
41
Restructure the program so that the main program prompts the user and displays
the result but the actual conversion is performed in a separate function:
double CslToFahr (double x);
42
Lesson
Learning Outcome
At the end of the lesson the students can solved the following types of
problems:
a. understand the basic structure of the C++ program;
b. understand and use the basic data types;
c. recognize and use the keywords and variables;
d. understand and use the constant, character and escape sequence; and
e. understand and use the C typecasting/promotion.
Encircle Me
Directions: Circle the number of syntactically valid declaration:
1. Short years, long hour;
2. unsigned, short positive;
3. double short;
4. double dollars_and_cents;
5. char mi, int age;
6. int count = 10; count2 = count; neg_count = -count;
7. double x = 0, y =1, r = x*x + y*y;
8. char A = A, C = 67, H = 72;
9. char CR = \n;
10. char exclamation_point = !;
43
True or False
Directions: Mark true or false:
1. The use of global variables is a sign of good program design.
2. If a local and a global variable have the same name, the compiler
reports a syntax
3. The typedef statement is used to rename variables.
4. The scope of a variable is the largest range of its values.
5. Local variables in different functions may have the same name.
6. Local variables in a function may have the same names as the
function arguments in its definition.
_______
_______
_______
_______
_______
_______
Do it yourself
Directions:
1. Assuming that the unsigned short data type is implemented as a two-byte binary
value, what is the largest possible value that an unsigned short variable can
hold? Give your answer as a decimal integer.
44
Lesson
ARITHMETIC EXPRESSIONS
Introduction
Variables and constants of integral and floating point types can be combined into
expressions using arithmetic operators. The arithmetic operators are listed in the following
table:
Operators
Description
45
Modulus
(
remainder from integer division
operands must be integeral
)
++
Increment by one;
can be prefix or postfix;
as postfix has highest precedence
--
Decrement by one;
can be prefix or postfix;
as postfix has highest precedence
Learning Outcome
At the end of the lesson the students can solved the following types of
problems:
a. identify the output program of different C++ statements;
b. fix the bugs of C++ program; and
c. write C++ program.
________________
________________
________________
________________
________________
________________
________________
46
3. short x, y;
cout <<Enter two integers x and y:;
cin>>x>>y;
x *=double (x);
y *=double (y);
double sq_radius = x+y;
if (sq_radius>250000)
cout<<(x,y) is outside the circle\n;
47
True or False
Directions: Mark true or false:
1. The result of the statement
int c = a + b++;
is always the same as the result of
int c = a + b + 1;
2. After executing the statements
w/=2;
w*=2;
the value of the int variable w always remains unchanged.
3. If the value of x is negative, the value of x%3 can be negative.
4. The value of (a_1) % 7 is always the same as the value of a%7+1.
48
Write a program
Directions:
1. Write a program that supports the following dialog with the user (the users input
is show in bold):
Enter deposit amount (dollar) ==> 900
Enter annual interest rate (%) ==> 6
Balance after 1 year:
Balance after 2 years:
Balance after 3 years:
956.00
1011.24
1071.91
Use a variable of an integral type to hold the initial balance entered by the user;
allow amount between 1 and $1,000,000. Use the simple interest formula: the
balance at the end of the year is equal to the balance at the beginning of the year
times (1+rate), where the rate is expressed as a decimal.
49
2. Write a program that prompts the user for his travel distance, the cars gas
mileage (mpg) and the price of gas, and displays the estimated cost of gas for
the trip.
50
Lesson
Learning Outcome
At the end of the lesson the students can solved the following types of
problems:
a. identify the rules of apvector and apmatrix classes;
b. identify the validity of apvector and apmatrix declaration; and
c. create a C++ program and fix the error.
True or False
Directions: Mark true or false:
1. The element of the array
char a[5];
are properly referred to as
a[1], a[2], a[3], a[4] and a[5]. ___________
2. The following array has 101 element:
int x[100]; _____________
3. The following array occupies 120 consecutive byte in memory:
short codes[600]; _______________
4. apvector is a reserved word. ____________
5. The apvector class reports an error when a subscript value is out of bounds.
________________
51
Valid or Invalid
Directions: Write valid or invalid in the following declaration:
1.
2.
3.
4.
5.
apvector x(100);
apvector<int> count;
apvector<double> coord[100];
apvector<int> odd(5) = { 1,2,3,5,7};
apvector<bool> flag (5,false);
___________
___________
___________
___________
___________
Test my Program
Directions: Enter the following declarations and assignments into a test program, compile,
and find out which of them cause problems:
#include apvector.h
apvector<int> a;
apvector<int>b(100);
apvector<double> x (100);
a = b;
x = b;
x = double (b);
___________
___________
___________
___________
___________
___________
Try to explain why?
52
53
Lesson
Learning Outcome
At the end of the lesson the students can solved the following types of
problems:
a.
b.
c.
54
_________________________________________________;
else if ( ________________________________________________ )
_______________________________________________________;
return x;
}
Write a function
Directions:
1. Write a function
double Max (double x, double y);
that returns the larger of the values x and y (or either, if they are equal).
2. Write a function
bool Later (int moth1, int day1, int year1, int month2, int day2, int year2);
that returns true if the second date is later than the first and false otherwise.
56
Simplify
Directions: Simply the following logical expression:
1.
if (!(x == 7) && !(x > 7))
________________________________________________
2.
bool inside = !((x < left) || (x > right) || (y < top)
|| y > bottom));
________________________________________________
3.
bool no = (ch[0] == 'N' && ch[1] == 'O') ||
(ch[0] == 'n' && ch[1] == 'o') ||
(ch[0] == 'n' && ch[1] == 'O');
________________________________________________
4. enum COLOR {WHITE, BLACK};
const int ROWS=480, COLS=640;
apmatrix<COLOR> pixels(ROWS, COLS);
...
int row, col;
...
if (pixels[row][col] == WHITE && pixels[row][col+1] == BLACK ||
pixels[row][col] == BLACK && pixels[row][col+1] == WHITE)
count++;
_________________________________________________
57
Problem Solving
Directions:
1.
Priority mail costs $3.00 for the first two pounds and $1.00 for each additional
pound or fraction. First class mail costs 32 cents for the first ounce and 23 cents
for each additional ounce or fraction, up to 11 ounces, after which priority rates
apply. Fill in the blanks in the following function:
58
2.
59
Lesson
Learning Outcome
At the end of the lesson the students can solved the following types of
problems:
a. understand and use the syntax of while, for, and do-while in creating
C++ program;
b. write appropriate function for iterative statement; and
c. solved and create C++ computer programming problems that involves
while, for, and do-while.
60
Find my Behavior
Directions: Describe the behavior of the following program: Write your answer in the box
provided.
#include <iostream.h>
int main()
{
int count = 0;
while (count <= 1) count += 0.1;
cout << count << endl;
return 0;
}
A) Syntax errorswill not compile
B) Displays 1.1
C) Displays 1
D) Goes into an infinite loop
E) Displays 0
int i, n = ___________________;
for (_____________________________________________________)
__________________________________________________;
}
2. Fill in the blanks in the following function:
int AlternateSum(const apvector<int> &v)
// Returns
// v[0] v[1] + v[2] v[3] + ... v[n1],
// where n is the number of elements. Assumes that n is even.
{
int i, n = v.length(), sum = 0;
for ( __________________________________________________ ) {
___________________________________________________
___________________________________________________
}
return sum;
}
Write a Function
Directions:
1. Write a function
double pow(double x, int n);
that returns the value of xn
.
Assume that x 0, n 0.
62
3. Write a function that returns the value of the largest positive element in a 2-D
array, or 0 if all its elements are negative:
double PositiveMax(const apmatrix<double> &m)
// Returns the value of the largest positive element in
// the matrix m, or 0, if all its elements are negative.
{
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
__________________________________________________________
}
63
Problem Solving
64
Write a test program that defines and initializes (or lets the user enter) two arrays
and displays their long sum.
65
Part III
Lesson
JAVA Programming
Introduction
Java is an object-oriented language similar to C++, but simplified to eliminate
language features that cause common programming errors. Java source code files (files
with a .java extension) are compiled into a format called bytecode (files with a .class
extension), which can then be executed by a Java interpreter. Compiled Java code can
run on most computers because Java interpreters and runtime environments, known as
Java Virtual Machines (VMs), exist for most operating systems, including UNIX, the
Macintosh OS, and Windows. Bytecode can also be converted directly into machine
language instructions by a just-in-time compiler (JIT). In 2007, most Java technologies
were released under the GNU General Public License
Learning Outcome
At the end of the lesson the students can solved the following types of
problems:
a. understand the basic structure of JAVA programming language;
b. understand and use java classes, methods, arrays, and basic
operation in creating java program; and
c. solved and create java computer program.
True or False
Directions: Write T if the statement is True otherwise F if False:
1. The modulus operator (%) in Java can be used only with variables of integer type.
66
3. All bitwise operations are carried out with the same level of precedence in Java.
4. The operations y >> 3 and y >>> 3 produce the same result when y > 0.
5. consider the statement "x = (a > b) ? a : b"; then the value of x is 27, if a = 18 and
b = 27.
8. The "switch" selection structure must end with the default case.
9. For the expression (y >= z && a == b) to be true, at least one of (y >= z) and (a ==
b) must be true.
10. A break statement must always be present in the default case of a "switch"
selection structure.
11. Variables declared inside a for loop are limited in scope to the loop.
12. An array in the Java programming language has the ability to store many different
types of values.
13. An individual array element from an array of type int, when passed to a method is
passed by value.
67
17. A static method can refer to any instance variable of the class.
18. All interface methods must be declared as public when implemented in a class.
19. Methods can be overloaded with a difference only in the type of the return variable.
20. A method in a class declared as static can only access static class members.
21. A method in a class declared as static may be invoked simply by using the name
of the method alone.
23. Java does not allow a method with the same signature in a subclass, as a method
in the super class.
28. A method that is overridden in the subclass must retain the same return type and
parameter list.
Multiple Choice
Directions: Write the letter of your choice only:
1. When we invoke repaint() for a java.awt.Component object, the AWT invokes
the method:
a. update()
b. draw()
c. show()
d. paint()
2. What does the following line of code do?
Textfield text = new Textfield(10);
a. creates text object that can hold 10 rows of text.
b. creates the object text and initializes it with the value 10.
c. The code is illegal.
d. Creates text object that can hold 10 columns of text.
3. Which of the following applet tags is legal to embed an applet class named Test
into a Web page?
a. < applet
class = Test width = 200 height = 100>
b. < applet>
code = Test.class width = 200 height = 100>
c. < applet
code = Test.class width = 200 height = 100>
d. < applet
code = Test.class width = 200 height = 100
e. < applet
param = Test.class width = 200 height = 100>
69
4. Which of the following methods can be used to draw the outline of a square
within a java.awt.Component object?
(A) fillRect()
(B) drawLine()
(B) drawLine()
(D) drawString()
(E) drawPolygon()
a. (B), (C) & (E)
b. (A), (B), (C) & (E)
c. (A), (B) & (C)
d. (C), (D) & (E)
e. (B) & (C)
5. Which of the following methods can be used to change the size of a
java.awt.Component object?
(A) dimension()
(B) setSize()
(C) area()
(D) size()
(E) resize()
a.
b.
c.
d.
e.
(A) "r"
(B) "w"
(C) "rw"
(D) "wr"
(E) "0"
a. (A), (B), (C) & (E)
b. (A) & (C)
c. (A), (B) & (C)
d. (B), (D) & (E)
e. (C) & (D)
9. DataInput is
a. an abstract class defined in java.io.
b. a class we can use to read primitive data types.
c. an interface that defines methods to read primitive data types.
d. an interface that defines methods to open files.
10. Which of the following statements are true?
(A) Unicode characters are all 16 bits.
(B) UTF characters are all 24 bits.
(C) Reader class has methods that can read integers and floats.
(D) File class may be used to rename a file.
(E) DataOutputStream objects are used to write primitive data to a file.
a. (A), (C), (D) & (E)
b. (A), (B) & (D)
c. (B), (D) & (E)
d. (A), (D) & (E)
e. (A) & (D)
11. Which are the valid ways to create DataInputStream streams?
a. new DataInputStream();
b. new DataInputStream("in.dat", "r");
c. new DataInputStream("in.dat")
d. new DataInputStream(new FileInputStream("in.dat");
e. new DataInputStream(new File("in.dat"));
12. Which exception is thrown by the read() method of InputStream class?
a. Exception
b. IOException
c. FileNotFoundException
d. ReadException
e. None of these
71
13. If you want to assign a value of 99 to the variable year, then which of the
following lines can be used within an tag?
a. number = getParameter(99)
b. < number = 99 >
c. < param = radius value = 99 >
d. < param name = number value = 99 >
e. < param number = 99 >
14. Given file is a File object, which of the following are legal statements to create a
new file?
(A) file.create();
(B) FileOutputStream fos = new FileOutputStream(file);
(C) FileWrter out = new FileWriter(file);
(D) FileInputStream fis = new FileInputStream(file);
(E) RandomAccessFile raf = new RandomAccessFile(file);
a. (B), (C) & (E)
b. (A), (B), (D) & (E)
c. (B), (C) & (D)
d. (B), (D) & (E)
e. (B) & (C)
15. Which of the following statements about abstract methods/classes in Java are
true?
1. An abstract class cannot be instantiated.
2. Constructors cannot be abstract.
3. A subclass of an abstract class must defined the abstract methods.
4. Static methods may be declared abstract.
a. Line 1, line 2 and line 3 only
b. Line 1 only
c. Line 1 and line 2 only
d. Line 2 only
e. All are true
16. Which keyword can protect a class in a package from accessibility by the
classes outside the package?
a. don't use any keyword at all (make it default)
b. private
c. protected
d. final
17. We would like to make a member of a class visible in all subclasses regardless of
what package they are in. Which one of the following keywords would achieve
this?
a. private
b. protected
c. private OR protected
d. public
72
18. The use of protected keyword to a member in a class will restrict its visibility as
follows:
a. Visible in all classes in the same package and subclasses in other packages.
b. Visible only in the class and its subclass in the same package.
c. Visible only inside the package.
d. Visible only in the class where it is declared.
19. Which of the following are not keywords?
(A) NULL
(B) implements
(C) protected
(D) extended
(E) string
a. (C), (D) & (E)
b. (A), (D) & (E)
c. (D) & (E)
d. (D)
20. Which of the following are keywords?
(A) switch
(B) integer
(C) default
(D) boolean
(E) object
a. (B) & (C)
b. (A) & (C)
c. (D)
d. (E)
21. Which of the following keywords are used to control access to a class member?
(A) default
(B) abstract
(C) protected
(D) interface
(E) public
a. (C) & (E)
b. (A), (C) & (E)
c. All of these.
d. (B), (C) & (E)
22. The keywords reserved but not used in the initial version of Java are:
(A) union
(B) const
(C) inner
(D) goto
(E) boolean
(F) synchronized
73
c. (B)
d. (A) & (C
33. Determine the output when the value of x is zero:
if(x >= 0)
if(x > 0)
System.out.println("x is positive");
else
System.out.println("x is negative");
a. "x is negative"
b. "x is positive"
c. "x is positive" and "x is negative"
d. None of these
34. The control expression in an "if" statement must be:
a. an expression with type integer
b. an expression with either the type boolean or integer
c. an expression with either the type boolean or integer with value 0 or 1
d. an expression with type Boolean
35. To print the value of a variable "x" of type int, which of the following expressions
can be used:
(A) System.out.println("x = " + x);
(B) System.out.println("x = " + String.valueOf(x));
(C) System.out.println("x = " + Integer.toString(x));
(D) System.out.println("x = " + (new Integer(x)).toString());
a. (B), (C) and (D)
b. (B) and (D)
c. (C) and (D)
d. (A), (B), (C) and (D)
36. Consider the following code:
int i = 1;
switch(c)
a. output will be One, followed by Two, and then followed by Three
b. output will be One followed by Two
c. output will be One
d. code is illegal and therefore will not compile
37. Consider the following code:
class NewString extends java.lang.String
a. Results in error because class body is not defined
b. Results in error because the class is not declaredpublic
c. Results in error because String isabstract
76
d. Compiles successfully
e. Results in error because java.lang.String isfinal
38. Examine the following class definitions to detect errors, if any.
abstract class MyPanel
a. 1 Error. Method show() should have a return type
b. 1 Error. Method show() is not implemented in MyDisplay
c. 1 Error. MyDisplay does not contain any members
d. No errors
39. Are there any errors in the following class definition?
abstract class Class1
a. Class header definition is wrong
b. Method definition is wrong
c. Constructor needs to be defined
d. No errors
40. For the following class definition, which is a legal statement to construct an object
of type Class1:
class Class1 extends Class2
a. (A)
b. (C) & (E)
c. (A) & (B)
d. (C) & (D)
e. None of the above
41. The method int func(int i, int j)
a. (B) & (C)
b. (C) & (D)
c. (A), (B), (C) & (E)
d. (A), (B) & (E)
e. None of these
42. Which error does the following code contain: class Class1
a. There is no error
b. Method func1() must be declared as static
c. Class Class1 has not been declared public
d. Class1 should be declared as abstract
43. What will be the output of the following program?
class Main1
a. XXX
b. YYY
77
78
Flash Card
Directions:
1. What will be the output of the following code?
byte x = 64, y;
y = (byte) (x << 2);
System.out.println(y);
Answer: ________
2. What will be the output of the following code?
byte b;
double d = 417.35;
b = (byte) d; System.out.println(b);
Answer: _________
3. Given the value of a variable, write a statement, without using if construct, which
will produce the absolute value of the variable.
Answer: __________
4. What is wrong with the following code?
switch (x)
{
case 1:
n1 = 10;
n2 = 20;
case 2:
n3 = 30;
break;
n4 = 40;
79
5.
6.
7.
8.
9.
}
Answer: ____________________
What will be the output of the following program code?
int m = 100;
int n = 300;
while(++m < --n);
System.out.println(m);
Answer:
What does the following fragment display?
String s = "six:" + 3 + 3;
System.out.println(s);
Answer: _________
What is the output of the following code?
String s;
System.out.println("s = " + s);
Answer: _________
What is the output of the following code?
String s = new String();
System.out.println("s = " + s);
Answer: ________
What is the problem with the following snippet?
class Q9
Answer: ______________________
10. What will be the output of the following code snippet?
int x = 10;
int y = 20;
if((x||(x=5)>10)
System.out.println(x);
else
System.out.println(y);
Answer: ______
11. Show the output of the following code:
int a, b;
a = 5;
b = 10;
if(a > 5)
if(b > 5)
{
System.out.println("b is " +b);
}
else
80
81
Do it yourself
Directions:
1. Write a Java program to display Hello World on the screen.
Write your code here:
82
3. Write a Java program to declare two integer variables, one float variable, and one
string variable and assign 10, 12.5, and "Java programming" to them respectively.
Then display their values on the screen.
Write your code here:
83
5. Write Java program to allow the user to input two integer values and then the
program prints the results of adding, subtracting, multiplying, and dividing among
the two values.
See the example below:
Enter value a:30
Enter value b:10
The result of adding is 40.
The result of subtracting is 20;
The result of multiplying is 300.
The result of dividing is 3.
Write your code here:
84
7. Write Java program to allow the user to input two float values and then the program
adds the two values together. The result will be assigned to the first variable.
Enter value a:12.5
The value of a before adding is 12.5.
Enter value b:34.9
The value of a after adding is 47.4.
Write your code here:
8. Write Java program to allow the user to input the amount of deposit, yearly interest
rate (percentage), and income tax(percentage). Then the program will calculate
the amount of interest that the person earns in the year. See the example output
below:
The amount of deposit: 1000
Yearly interest rate: 7.5%
Income tax rate: 4%
The amount of interest earned in the year:71.0
85
9. Write Java program to allow the user to input his/her age. Then the program will
show if the person is eligible to vote. A person who is eligible to vote must be older
than or equal to 18 years old.
Enter your age: 18
You are eligible to vote.
86
10. Write a Java program to determine whether an input number is an even number.
Write your code here:
87
12. Write a Java program to calculate the revenue from a sale based on the unit price
and quantity of a product input by the user.
The discount rate is 10% for the quantity purchased between 100 and 120 units,
and 15% for the quantity purchased greater than 120 units. If the quantity
purchased is less than 100 units, the discount rate is 0%. See the example output
as shown below:
Enter unit price: 25
Enter quantity: 110
The revenue from sale: 2475.0$
After discount: 275.0$(10.0%)
88
13. Write a Java program by using two for loops to produce the output shown below:
*******
******
*****
****
***
**
*
89
14. Write Java program to prompt the user to choose the correct answer from a list of
answer choices of a question.
The user can choose to continue answering the question or stop answering it.
See the example below:
What is the command keyword to exit a loop in Java?
a. int
b. continue
c. break
d. exit
Enter your choice: b
Incorrect!
Again? press y to continue:
Write your code here:
90
15. By using do while loop, write Java program to prompt the user to choose the
correct answer from a list of answer choices of a question.
The user can choose to continue answering the question or stop answering it.
See the example below:
What is the command keyword to exit a loop in Java?
a. int
b. continue
c. break
d. exit
Enter your choice: b
Incorrect!
Again? press y to continue:
Write your code here:
91
Answer Key:
Part I.
Lesson 1.
Activity 1: Fill in the Blank
Bit Value
Position value as
a power of base 2
Bit number
1
128
1
64
1
32
1
16
1
8
1
4
1
2
1
1
Activity 2: Complete Me
Decimal Number
Binary Representation
0
0000
1
0001
2
0010
3
0011
4
0100
5
0101
6
0110
7
0111
8
1000
9
1001
10
1010
11
1011
12
1100
13
1101
14
1110
15
1111
Hexadecimal Representation
0
1
2
3
4
5
6
7
8
9
A
B
C
D
E
F
6. 12 = 00001100
7. 15 = 00001111
8. 16 = 00010000
9. 20 = 00010100
10. 27 = 00011011
00000101 = 5
00001111 = 15
00010000 = 16
00010110 = 22
6. 00011100 = 28
7. 00110000 = 48
8. 00100111 = 39
9. 01000000 = 64
92
10. 00001011 = 11
Activity 5: Binary to Hexadecimal
10. 01100011 = 99
6. 00000101 = 05h
7. 00001111 = 0Fh
8. 00010000 = 10h
9. 00010110 = 16h
10. 00001011 = 0Bh
Activity 6: Hexadecimal to Binary
6. 00011100 = 1Ch
7. 00110000 = 30h
8. 00100111 = 27h
9. 01001000 = 48h
10. 01100011 =63h
6. 0005h = 00000101
7. 000Fh = 00001111
8. 0010h = 00010000
9. 0016h = 00010110
10. 000Bh = 00001011
6. 001C = 00011100
7. 0030h = 00110000
8. 0027h = 00100111
9. 0048h = 01001000
10. 0063h = 01100011
213
47
272
534
75
6. 041Ch = 1052
7. 0B30h = 2864
8. 06DFh = 1759
9. 1AB6h = 6838
10. 0A63h =2659
Lesson 2.
Activity 1: My negative side
1. 11001011
2. 11001011
3. 11001011
4. 11001011
5. 11001011
Activity 2: 8-bit binary notation
5.
6.
7.
8.
-2 = 11111110
-7 = 11111001
-128 = 10000000
-16 = 11110000
5. +15 = 00001111
6. -1 = 11111111
7. -56 = 11001000
8. +127 = 01111111
Column B
9. 11111111
10. 11110000
1. +15
2. -16
93
11. 10000000
12. 10000001
13. 00001111
14. 10101111
15. 11111100
16. 01010101
3. +85
4. -4
5. -1
6. -127
7. -128
8. -81
5.
6.
7.
8.
7FB9h = P
8123h = N
0D000h = N
649Fh = P
-42 = FFD6h
-127 = FF81h
-4096 = F000h
-16 = FFF0h
5. -32768 = 8000h
6. -1= FFFFH
7. -8193 = DFFFH
8. -256 = FFOh
Lesson 3.
Activity 2: Base 10 Fraction and Decimal
Binary Floating point
1.101
11.11
1.1
101.001
1101.0101
1110.00111
10000.101011
111.0000011
11.000101
Base 10 Fraction
1 5/8
3 3/4
1 1/2
5 1/8
13 5/16
14 7/32
16 43/64
7 3/128
3 5/64
Base 10 Decimal
1.625
3.75
1.5
5.125
13.3125
14.21875
16.671875
7.0234375
3.078125
94
Binary Representation
10000001
10000100
01111111
01110101
11111111
01111110
Normalized As
1.000011
1.101101
1.01
1.0001
1.0000011
1.1001
Exponent
4
3
-3
0
7
-6
Lesson 4.
Activity 1: Valid or Invalid
11. mov ax, bx = V
Valid or Invalid
V
I
I
V
I
I
I
V
V
I
CY
9. mov bh, 2
sub bh, 2
NC
CY
NC
CY
ZR
4. mov
NX
96
add ax, 1
al, 0DFh
add
al, 32h
5. mov bh, 2
sub bh, 2
ZR
6. mov dx, 0
dec dx
NZ
5. mov
si , 0B9F6h
sub
si,9874h
NZ
6. mov
cx, 695Fh
add
cx,96A1h
ZR
PL
5. mov bh, 2
sub bh, 3
6. mov dx, 0
dec dx
NG
NG
4. mov
ax, 7FFEh
add
ax, 22h
5. mov
si, 0B9F6h
sub
si, 9874h
6. mov
cx, 8000h
add
cx, A69Fh
cx,96A1h
NG
PL
PL
CY, PL, NZ
NC, PL, NZ
6. mov
CY, NG, NZ
97
ax, 0B6D4h
add
al, 0B3h
Lesson 5.
Activity 1: Valid or Invalid
4. Mov
ax, byteVal
4. mov
si, aString
5. Mov
dx, wordVal
6. Mov
ecx, dwordVal
5. mov
esi, offset
aString
6. mov
al, byteVal
4. mov
si, dwordVal
5. mov
esi, offset
aString+2
6. mov
V
ecx, offset
dwordVal
Activity 3: Hexadecimal Value
4. mov
ax, offset
byteVal
000000000h
5. mov
dx, wordVal
1000h
6. mov
ecx, dwordVal
12345678h
6. mov
al, offset
byteVal+1
4. mov
esi, offset
wordVal
00000014h
5. mov
esi, offset
aString
43h (C)
6. mov
al, aString+2
0000000Ch
wordVal
00000004h
4. mov
esi, offset
wordVal+4
00000002h
5. mov
dx, wordVal+4
3000h
00000008h
5. mov
esi, offset
aString-1
00000013h
6. mov
ecx, dwordVal+4
3456780h
4. mov
si, dwordValSiz
00000006h
5. mov
dx, wordVal+4
0002h
0010h
5. mov
al, byteVal+4
58h (X)
6. mov
ecx, dwordVal+4
0000007h
5. mov
dx, wordVal-2
5958h (YX)
5. mov
esi, ptrWord
00000006h
6. mov
edi, offset
dwordVal+2
000000Eh
99
6. mov
eax, ptrByte
00000000h
Part II.
Lesson 6.
Activity 1. H o S
1. Operating system
2. CPU
3. Compiler
4. Program editor
5. IDE
6. GUI (Graphical User Interface)
7. Assembler
8. Bus
9. RAM
10. ROM
11. File
12. Modem
_____S______
____H_______
_____S______
_____S______
_____S______
_____S______
_____S______
_____H______
______H_____
_______H____
______S_____
_______H____
Part III.
Activity 1: True or False
1. F
2. F
3. F
4. T
5. T
6. T
7. F
8. F
9. F
10. F
11. F
12. F
13. T
14. F
15. T
16. T
17. F
18. T
19. F
20. T
21. F
22. F
23. F
24. T
25. F
26. F
27. T
28. T
29. F
5. d
6. d
7. d
8. b
9. c
10. d
11. d
12. b
1. a
2. d
3. c
4. a
100
13. d
14. a
15. c
16. a
17. c
18. a
19. b
20. b
21. d
22. c
23. d
24. d
25. d
26. c
27. b
28. b
29. a
30. c
31. a
32. b
33. a
34. d
35. d
36. a
37. e
38. b
39. b
40. d
41. d
42. d
43. c
44. b
45. b
46. b
47. e
48. c
49. b
50. c
19
Activity 4: Do it
yourself
System.out.println("*****");
1. public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello
World.");
}
}
2. public class JavaExercises
{
public static void main(String[] args)
{
printAsterisk();
}
static void printAsterisk(){
System.out.println("*****");
System.out.println("*****");
System.out.println("*****");
System.out.println("*****");
4. import java.io.*;
public class
JavaExercises
{
public static void
main(String[] args)
{
printName();
}
static void
printName(){
String pname=null;
try{
BufferedReader
br=new
}
}
3. public class JavaExercises
{
public static void main(String[] args)
{
accessVariables();
}
static void accessVariables(){
int x;
float y;
String s;
x = 10;
y = 12.5f;
s = "Java programming";
System.out.println(x);
System.out.println(y);
System.out.println(s);
}
}
BufferedReader(ne
w
InputStreamReader
(System.in));
System.out.print(
"Enter your
name:");
pname=br.readLi
ne();
}catch(IOExceptio
n e){}
}
5. import
java.util.Scanner;
public class
JavaExercises
{
public static void
main(String[] args)
{
caculateValues();
}
System.out.println(
"Hello "+pname);
static void
caculateValues(){
int a,b;
19
int
resulta,results,result
m;
float resultd;
Scanner sc=new
Scanner(System.in)
;
System.out.print("E
nter a:");
a=sc.nextInt();
System.out.print("E
nter b:");
b=sc.nextInt();
resulta=a+b;
results=a-b;
resultm=a*b;
resultd=(float)a/b;
System.out.println(
"The result of
adding is
"+resulta);
System.out.println(
"The result of
subtracting is
"+results);
System.out.println(
"The result of
multiplying is
"+resultm);
System.out.println(
"The result of
dividing is
"+resultd);
}
}
6. public class
JavaExercises
{
public static void
main(String[] args)
{
caculateValues();
}
("The value of a
after adding:"+a);
static void
caculateValues(){
int a;
Random rn=new
Random();
a=1+Math.abs(rn.n
extInt()%6);
System.out.println(
"The result: "+a);
}
}
7. import java.util.*;
public class
JavaExercises
{
public static void
main(String[] args)
{
caculateValues();
}
static void
caculateValues(){
float a;
float b;
Scanner sc=new
Scanner(System.in)
;
System.out.print("
Enter a:");
a=sc.nextFloat();
System.out.println
("The value of a
before adding:"+a);
System.out.print("
Enter b:");
b=sc.nextFloat();
a+=b;
System.out.println
}
}
8.
import java.util.*;
public class
JavaExercises
{
public static void
main(String[] args)
{
caculateInterest();
}
static void
caculateInterest(){
float amount_dep,
rate, tax,
interest_earned,
tax_amount;
Scanner sc=new
Scanner(System.in);
System.out.print("Ent
er the amount of
deposit:");
amount_dep=sc.nextF
loat();
System.out.print("Ent
er yearly interest
rate:");
rate=sc.nextFloat();
interest_earned=amo
unt_dep*(rate/100);
//amount of interest
before tax calculation
System.out.print("Ent
er income tax rate:");
tax=sc.nextFloat();
tax_amount=interest_
earned*(tax/100);
interest_earned-=tax;
//the final interest
earned
System.out.println("T
he interest earned in
the
19
year:"+interest_earned
);
}
}
9.
import java.util.*;
public class
JavaExercises
{
public static void
main(String[] args)
{
checkEligibility();
}
static void
checkEligibility(){
int age;
Scanner sc=new
Scanner(System.in)
;
System.out.print("
What is your
age?");
age=sc.nextInt();
if(age>=18)
System.out.println(
"You are eligible to
vote.");
else
System.out.println(
"You are not
eligible to vote.");
}
}
10. import java.util.*;
public class
JavaExercises
{
public static void
main(String[] args)
{
determineEven();
}
static void
determineEven(){
int num=0;
Scanner sc=new
Scanner(System.in)
;
System.out.print("E
nter a number:");
num=sc.nextInt();
if(num%2==0)
System.out.println(
"It is an even
number.");
else
System.out.println(
"It is an odd
number.");
}
}
mid_score,final_sc
ore,avg;
Scanner sc=new
Scanner(System.in)
;
System.out.print("
Quiz score:");
quiz_score=sc.next
Float();
System.out.print("
Mid-term score:");
mid_score=sc.next
Float();
System.out.print("F
inal score:");
final_score=sc.next
Float();
avg=(quiz_score+
mid_score+final_sc
ore)/3;
if(avg>=90)
System.out.println(
"Your grade A.");
else if((avg>=70)
&& (avg<90))
System.out.println(
"Your grade B.");
else if((avg>=50)
&& (avg<70))
System.out.println(
"Your grade C.");
else if(avg<50)
System.out.println(
"Your grade F.");
else
System.out.println(
"Invalid");
}
}
12. import java.util.*;
public class
JavaExercises
20
{
public static void
main(String[] args)
{
calculateSale();
}
revenue=discount_amount;
}
float unitprice=0f;
int quantity=0;
float revenue=0f;
float
discount_rate=0f,
discount_amount=
0f;
else
if(quantity>120)
{
discount_rate=(floa
t)15/100;
revenue=unitprice*
quantity;
discount_amount=
revenue*discount_
rate;
revenue=discount_amount;
}
Scanner sc=new
Scanner(System.in)
;
System.out.print("E
nter unit price:");
unitprice=sc.nextFl
oat();
System.out.print("E
nter quantity:");
quantity=sc.nextInt
();
System.out.println(
"The revenue from
sale:"+revenue+"$"
);
System.out.println(
"After
discount:"+discoun
t_amount+"$("+dis
count_rate*100+"
%)");
}
if(quantity<100)
revenue=unitprice*
quantity;
else
if(quantity>=100
&& quantity<=120)
{
discount_rate=(floa
t)10/100;
revenue=unitprice*
quantity;
discount_amount=
revenue*discount_
rate;
static void
calculateSale(){
int i,j;
for(i=0;i<=6;i++){
for(j=1;j<=7-i;j++)
System.out.print("*
");
System.out.println(
"");
}
}
}
14.
import java.io.*;
public class
JavaExercises
{
public static void
main(String[] args)
{
selectChoice();
}
static void
selectChoice(){
String choice;
String con="y";
try{
BufferedReader
br=new
BufferedReader(ne
w
InputStreamReader
(System.in));
System.out.println(
"What is the
command keyword
to exit a loop in
Java?");
System.out.println(
"a.quit");
System.out.println(
21
"b.continue");
System.out.println(
"c.break");
System.out.println(
"d.exit");
while
(con.compareTo("y
")==0)
{
System.out.print("E
nter your choice:");
choice
=br.readLine();
if
(choice.compareTo
("c")==0)
{
System.out.println(
"Congratulation!");
}
else if
(choice.compareTo
("q")==0 ||
choice.compareTo(
"e")==0)
{ System.out.printl
n("Exiting...!");
break; }
else
System.out.println(
"Incorrect!");
System.out.print("
Again? press y to
continue:");
con =br.readLine();
}
}catch(IOException
e){}
}
}
15. import java.io.*;
public class
JavaExercises
{
public static void
main(String[] args)
{
selectChoice();
}
static void
selectChoice(){
String choice;
String con;
try{
BufferedReader
br=new
BufferedReader(ne
w
InputStreamReader
(System.in));
System.out.println(
"What is the
command keyword
to exit a loop in
Java?");
System.out.println(
"a.quit");
System.out.println(
"b.continue");
System.out.println(
"c.break");
System.out.println(
"d.exit");
}
}
do
{
System.out.print("E
22
References:
ebook:
M. Litvin and G. Litvin, Workbook to Accompany C++ for You++, Skylight
Publishing, 1998
Kip R. Irvine. 2008, Assembly Language Workbook, Prentice-Hall
Addison-Wesley, (2013), The C++ Programming Language (4th Edition)
Backman, K., (2012), Structured Programming with C++
Bronson, G.J., (2006), Program Development and Design using C++
Intenet:
http://www.skylit.com.