Você está na página 1de 109

Republic of the Philippines

SULTAN KUDARAT STATE UNIVERSITY


Kalamansig Campus
Kalamansig, Sultan Kudarat

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 3: Supply the actual binary bits


Activity 4: Supply the normalized value and resulting exponent
Activity 5: Supply the complete binary
Practice and Application
Activity 6: Do it yourself
Closure
Activity 7: Show Me the Value
Lesson 4: Addition and Subtraction Instructions
Introduction
Learning Outcome
Activating Prior Knowledge
Activity 1: Valid or Invalid
Setting the Context
Activity 2: Valid or Invalid
Activity 3: Carry or No carry
Activity 4: Zero or Not Zero
Activity 5: Positive or Negative
Activity 6: Carry, Sign, and Zero
Practice and Application
Activity 7: Do it yourself
Lesson 5: Direct Memory Operands
Introduction
Learning Outcome
Activating Prior Knowledge
Activity 1: Valid or Invalid
Activity 2: Valid or Invalid
Setting the Context
Activity 3: Hexadecimal Value
Activity 4: Hexadecimal Value
Activity 5: Hexadecimal Value
Activity 6: Hexadecimal Value
Practice and Application
Activity 7: Do it yourself
Part II: VC++
Lesson 6: Introduction to Hardware and Software
Introduction
Learning Outcome
Activating Prior Knowledge
Activity 1: H or S
Setting the Context
Activity 2: Guess Me
Activity 3: 8-bit to decimal and hex
Activity 4: 16-bit to decimal and hex
Activity 5: ASCII codes in decimal, hex and binary
Activity 6: Solve for x
Practice and Application
3

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

Lesson 11: Logical Expressions and If-else Statements


Introduction
Learning Outcome
Activating Prior Knowledge
Activity 1: Fill in the Blank
Setting the Context
Activity 2: Write a function
Activity 3: Simplify
Practice and Application
Activity 4: Problem Solving
Lesson 12: Iterative Statements: while, for, do-while
Introduction
Learning Outcome
Activating Prior Knowledge
Activity 1: Find my Behavior
Setting the Context
Activity 2: Fill in the Blank
Activity 3: Write a Function
Practice and Application
Activity 4: Problem Solving
Part III: JAVA
Lesson 13: JAVA Programming Basic
Introduction
Learning Outcome
Activating Prior Knowledge
Activity 1: True or False
Setting the Context
Activity 2: Multiple Choice
Activity 3: Flash Card
Practice and Application
Activity 4: Do it yourself
Answer Key
References

Part I
Lesson

BINARY AND HEXADECIMAL INTEGERS


Introduction
Every number system uses positional notation i.e., each position in which a digit is
written has a different positional value. Each position is power of the base, which is 2 for
binary number system, and these powers begin at 0 and increase by 1.
Hexadecimal number system uses base 16. The digits range from 0 to 15. By
convention, the letters A through F is used to represent the hexadecimal digits
corresponding to decimal values 10 through 15. Main use of hexadecimal numbers in
computing is for abbreviating lengthy binary representations. Basically hexadecimal
number system represents a binary data by dividing each byte in half and expressing the
value of each half-byte.

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.

Activating Prior Knowledge

Fill the Box


Directions: Fill the missing positional values for an 8-bit binary number, where all bits
are set on. Bit number 7 was already done for you.

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

Setting the Context

Conversion: Decimal to Binary


Directions: Write each of the following decimal numbers in binary:
1. 2 =

6. 12 =

2. 7 =

7. 15 =

3. 5 =

8. 16 =

4. 8 =

9. 20 =

5. 9 =

10. 27 =

Conversion: Binary to Decimal


Directions: Write each of the following binary numbers in decimal:
1. 00000101 =

6. 00011100 =

2. 00001111 =

7. 00110000 =

3. 00010000 =

8. 00100111 =

4. 00010110 =

9. 01000000 =

5. 00001011 =

10. 01100011 =

Conversion: Binary to Hexadecimal


Directions: Write each of the following binary numbers in hexadecimal:
1. 00000101 =

6. 00011100 =

2. 00001111 =

7. 00110000 =

3. 00010000 =

8. 00100111 =

4. 00010110 =

9. 01001000 =

5. 00001011 =

10. 01100011 =

Conversion: Hexadecimal to Binary


Directions: Write each of the following hexadecimal numbers in binary:
1. 0005h =

6. 001C =

2. 000Fh =

7. 0030h =

3. 0010h =

8. 0027h =

4. 0016h =

9. 0048h =
8

5. 000Bh =

10. 0063h =

Conversion: Hexadecimal to Decimal


Directions: Write each of the following Hexadecimal numbers in Decimal:
1. 00D5h =

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:

Practice and Application

DO it yourself
Directions:
1. Convert the following binary numbers to their decimal representation:
a. 11 =

c. 111011 =

b. 1101 =

d. 0101 =

2. Convert the following hexadecimal numbers to their decimal representation:


a. 11=

c. CEF =

b. A1 =

d. BA9 =

3. Convert the following decimal numbers to their hexadecimal and binary


representation:
a. 11 =

c. 42 =

b. 4000 =

d. 4095 =

4. Do the binary arithmetic:


a. 10110 + 01101 =
b. 11001 + 00101 =
11

c. 10110 01101 =
d. 11111 01011 =
5. Do the hexadecimal arithmetic:
a. 82CD + 1982 =

c. FB28 3254 =

b. E2C + A31 =

d. E2C A31 =

6. The integers in the following computations are indicated in hexadecimal, but


represent 32 bit twos complement binary numbers. Perform the operations and
indicate if overflow occurs and why. (If overflow occurs the result is invalid, but
show it anyway.)
a. BBCA270C
+AE223464

d. 5FCA5243
+AE223464

b. E3BA265F
+ E045B9A9

e. 80000000
+7FFFFFFF

a. E9B20F5D
+FE605C8D

f. 6D4AFBC0
+F89ABCDE

Closure

Individual Work
Directions:
1.
2.
3.
4.

Write decimal numbers from 1 to 100 and convert it into binary.


From the converted binary convert it into hexadecimal.
Discuss your observation in converting binary and decimal numbers.
Use extra sheet of paper for all of your answer.

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.

Activating Prior Knowledge

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.

Setting the Context

8-bit binary notation


Directions: Write each of the following signed decimal integers in 8-bit binary notation:
If any number cannot be represented as a signed 8-bit binary number,
indicate this in your answer. Number 1 was already done for you. Write your
answer in the box provided.
1. -2

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

Practice and Application

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

2. 1753 8640 (4 digit)


Solution:

16

3. 20 40 (2 digits)
Solution:

4. 1200 250 (4 digit)


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:

2. 100 110000 (6 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.

Activating Prior Knowledge

Conversion: Fraction to Decimal


Directions: Convert the following fractions to decimal. Show your solution. Write your
answer in the box provided.
1. 0.10112

2. 0.21438

19

3. 101.1012

4. 0.00012

5. 101010.11112

Setting the Context

Base 10 Fraction and Decimal


Directions: For each of the following binary floating-point numbers, supply the equivalent
value as a base 10 fraction, and then as a base 10 decimal. The first problem
has been done for you:
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

Base 10 Decimal
1.625

20

Supply the actual binary bits


Directions: For each of the following exponent values, shown here in decimal, supply the
actual binary bits that would be used for an 8-bit exponent in the IEEE Short
Real format. The first answer has been supplied for you:

Exponent (E)
2
5
0
-10
128
-1

Binary Representation
10000001

Supply the normalized value and resulting exponent


Directions: For each of the following floating-point binary numbers, supply the normalized
value and the resulting exponent. The first answer has been supplied for you:
Binary Value
10000.11
1101.101
.00101
1.0001
10000011.0
.0000011001

Normalized As
1.000011

Exponent
4

Supply the complete binary


Directions: For each of the following floating-point binary examples, supply the complete
binary representation of the number in IEEE Short Real Format. The first
answer has been supplied for you:
Binary Value
-1.11
+1101.101
-.00101
+100111.0
+.0000001101011

Sign, Exponent, Mantissa


1 01111111 11000000000000000000000

21

Practice and Application

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

b. -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

Show Me the Value


Directions: Suppose you are working a 4-bit binary number system, using excess 8
notation. Write down all 16 bit patterns and show what their values would be
in unsigned binary, sign-magnitude, 2s complement and excess-8.

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

ADDITION AND SUBTRACTION INSTRUCTIONS


Introduction
The ADD and SUB instructions are used for performing simple addition/subtraction
of binary data in byte, word and double word size i.e., for adding or subtracting 8-bit, 16bit or 32-bit operands, respectively.

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.

Activating Prior Knowledge

Directions: Indicate whether or not each of the following MOV instructions is valid:
(notate: V = valid, I = invalid)
1. mov ax, bx =

11. mov edx,ax =

2. mov dx, bl =

12. mov ax,es =

3. mov ecx, edx =

13. mov ax,16 =

4. mov si,di =

14. mov dx,7F65h =

5. mov ds, ax =

15. mov ecx, 6F23458h=

6. mov ds,es =

16. mov si, -1 =

7. mov al, dh =

17. mov ds, 1000h =

8. mov ax,dh =

18. mov al, 100h =

9. mov ip,ax =

19. mov 123, dh =

10. mov si, cl =

20. mov ss, ds =


24

Setting the Context

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

Zero or Not Zero


Directions: What will be the value of the zero flag after each of the following instruction
sequences has executed?
(notate: ZR = zero, NZ = not zero)
1. mov ax, 0FFFFh
add ax, 1

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

Carry, Sign, and Zero


Directions: What will be the values of the Carry, Sign, and Zero flags after the following
instructions have executed?
(notate: CY/NC, PL/NG, ZR/NZ)
1. mov
ax, 620h
sub
ah, 0F6h
2. mov
ax, 720h
sub
ax, 0E6h
3. mov
ax, 0B6D4h
add
al, 0B3h

27

Practice and Application

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

DIRECT MEMORY OPERANDS


Introduction
A direct memory operand specifies the data at a given address. The instruction
acts on the contents of the address, not the address itself. Except when size is implied
by the operand, you must specify the size of a direct memory operand so the instruction
accesses the correct amount of memory. Any location in memory can be a memory
operand as long as a size is specified (or implied) and the location is fixed. The date at
the address can change, but the address cannot. By default, instructions that use direct
memory addressing use the DS register.

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.

Activating Prior Knowledge

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

Setting the Context

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

7. move di, offset


dwordVal

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

Practice and Application

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

INTRODUCTION TO HARDWARE AND SOFTWARE


Introduction
Hardware and Software have a symbiotic relationship, this means that without
software hardware is very limited; and without hardware, software wouldnt be able to rum
at all. They need each other to fulfill their potential.

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.

Activating Prior Knowledge

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

Setting the Context

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? _______________________________

8-bit to decimal and hex


Directions: Assume that these 8-bit binary numbers represent unsigned integers in the
usual way, with the least significant bit on the right. Write the decimal value
and the hex representation of these binary numbers.
Example:

1.
2.
3.
4.
5.
6.
7.

Binary
00011100

decimal
28

hex
1C

00000011
00001111
00101111
10000001
11000001
00001011
11110101

______________
______________
______________
______________
______________
______________
______________

______________
______________
______________
______________
______________
______________
______________

35

16-bit to decimal and hex


Directions: Assume that these 16-bit binary numbers represent unsigned integers in the
usual way, with the least significant bit on the right. Write the decimal value
and the hex representation of these binary numbers.
Example:

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

______________
______________
______________
______________
______________

______________
______________
______________
______________
______________

ASCII codes in decimal, hex and binary


Directions: Using the ASCII table, write the ASCII codes for the following characters in
decimal, hex and binary:

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

A FIRST LOOK AT A C++ PROGRAM


Introduction
C++ is an object oriented programming (OOP) language, developed by Bjarne
Stroustrup, and is an extension of C language. It is therefore possible to code C++ in a
C style or object-oriented style. In certain scenarios, it can be coded in either way and
is thus an effective example of a hybrid language. C++ is a general purpose object
oriented programming language. It is considered to be an intermediate level language, as
it encapsulates both high and low level programming features. Initially, the language was
called C with classes as it had all properties of C language with an additional concept of
classe. However, it was renamed to C++ in 1983. It is pronounced C-Plus-Plus.

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.

Activating Prior Knowledge

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.

The program has no function.


apstring is not a reserved word.
The program prompts the user to enter his or her name.
firstName is a C++ reserved word.
#include <iostream.h> is a preprocessor directive.
Each item displayed with the <<operator must be paced
on a separate line.
7. cout is a reserved word.

________
________
________
________
________
________
________

Setting the Context

Identification
Directions: Identify the following statements as referring to required C++ syntax or
optional C++ style:
1.
2.
3.
4.
5.
6.
7.
8.

A program begins with two slashes (//).


The names of all functions begin with a capital letter.
Each opening brace has a matching closing brace.
All statements within a pair of matching braces are
indented by 4 characters.
A closing brace is place on a separate line.
A program has a blank line before each function definition.
One of the functions in the program is called main.
The word IF is not used as a name for a variable.

________________
________________
________________
________________
________________
________________
________________
________________

True or False
Directions: Mark True or False.
1.
2.
3.
4.

CHAR is not a reserved word.


Each C++ statement must be written on a separate line.
Each preprocessor directive must be written on a separate line.
C++ functions can be called only from main ().

______
______
______
______
39

5. Each function must have a return statement.


6. The compiler automatically corrects syntax errors.
7. Programming languages usually have less redundancy than
natural languages.

______
______
______

Always, Sometimes, or Never


Directions: Complete each sentence with the word always, sometimes, or never:
1.
2.
3.
4.
5.

Function prototypes are ______________placed near the top of the program.


Function names ______________begin with the # symbol.
There is ______________a semicolon after a closing brace.
Program input ________________comes from cin.
Standard library functions prototypes are _______________provide in system
header files.

Fill in the Blank


Directions: Choose the right word to fill the blank:
1. #ifdef-#else-#endif
directives
are
used
for
conditional
____________(compilation/execution) of a program fragment.
2. The dict.dat file is ____________(compiled with/linked with/read by) the Dictionary
program.
3. The format of the dict.dat file in the Dictionary program must be compatible with
______________(C++ syntax/the operating system/the Load Dictionary()
function).

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. __________

Practice and Application

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

VARIABLES AND CONSTANTS


Introduction
In programming, a variable is a container (storage area) to hold data. To indicate
the storage area, each variable should be given a unique name (identifier). Variable
names are just the symbolic representation of a memory location. A constant is a value or
an identifier whose value cannot be altered in a program.

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.

Activating Prior Knowledge

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

Setting the Context

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.

_______
_______
_______
_______
_______
_______

Practice and Application

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.

2. What is the output of the following program?


#include <iostream.h>
int main()
{
double amt = 100.00;
cout<<sizeof(amt) sizeof(double)<<endl;
return 0;
}

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

Unary plus needs one operand.

Unary minus needs one operand.

Addition needs two operands.

Subtraction needs two operands.

Multiplication needs two operands.

Division needs two operands.


(
Floating point operands:
-- floating point result
Integer operands:
-- integer quotient
Mixed operands:
-- floating point result
)

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.

Activating Prior Knowledge

Find the Output


Directions: What is the output of the following statements?
1.
2.
3.
4.
5.
6.
7.

cout << 5.2/10<<endl;


cout <<5/10<<endl;
cout <<1/2 * 10<<endl;
cout <<1.2/2 ) 10<<endl;
cout <<1/2.2 *10<<endl;
cout <<5%10<<endl;
cout <<-5%10<<endl;

________________
________________
________________
________________
________________
________________
________________

46

Setting the Context

Fix the bug


Directions: Fix the bugs in the following statements: Write the fix code in the box
provided:
1. const short days = 365, hours = 24, mins = 60, secs = 60;
cout <<Seconds in a year =
<<hours *mins*secs*double(days)<<endl;

2. const double g = 16;


double t;
cout <<Enter time in secs:;
cin>>t;
cout<<The travel distance is<<1/2 * (g*t*t)
<<endl;

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.

Fill in the blank


Directions: Fill in the blanks in the following program that converts a number of minutes
into hour:minute.
#include <iostream.h>
#include <iomanip.h>
Int main ()
{
Int mins;
cout<< Enter the number of minutes:;
cin>>mins;
cout<<___________________________________<<:
<<setfill (0) // set output fill character to 0
<<setw(2) << ___________________________<<endl
<<setfill ( ); // restore the default fill char
return 0;
}

48

Practice and Application

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

ARRAYS, apvector and apmatrix CLASSES


Introduction
An array is a data structure which allows a collective name to be given to a group of
elements which all have the same type. An individual element of an array is identified by
its own unique index (or subscript). An array can be thought of as a collection of
numbered boxes each containing one data item.

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.

Activating Prior Knowledge

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

Setting the Context

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);

___________
___________
___________
___________
___________

Practice and Application

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

Fix the bug


Directions: The following statements should double the values of the elements of the array
scores. Find the bug.
int i;
apvector<int> scores(16);
.
i = 0;
// repeat as long as i does not exceed 16:
while (i <= 16) {
scores [i] *=2;
i++;
}

53

Lesson

Logical Expressions and if-else Statements


Introduction
Thus far, most of our labs have dealt solely with the sequence construct. In the sequence
construct each statement is executed in the order in which it occurs in the program.
However, many times our actions are dependent on certain conditions. For instance, if it
is raining outside, then you will take an umbrella. But if the sun is shining, you will leave
the umbrella at home. Similarly, a program might need to execute one statement if one
condition occurs, and execute a different statement if another condition occurs. For
example, if the account balance falls below 0, issue a statement saying the customer is
overdrawn, otherwise continue processing checks. In this lab you will learn how to write
C++ conditions (logical expressions), and you will learn one way of controlling which C++
statement is executed next (the if statement).

Learning Outcome
At the end of the lesson the students can solved the following types of
problems:
a.
b.
c.

Learn to use logical expressions


Learn to use if and if-else statements
Learn to use nested if statements

54

Activating Prior Knowledge

Fill in the Blank


Directions: Fill in the blanks the following functions:
1. bool is digit(char d)
// Returns true if d is a digit (in ASCII code), false otherwise.
{
return _______________________________________________
}
2. bool isalpha(char c)
// Returns true if c is a letter (in ASCII code),
// false otherwise.
{
return ________________________________________________
____________________________________________
}
3. int HexToDec(char hexdigit)
// Returns the decimal value of the corresponding hexadecimal
// digit, where "hexdigit" is a character '0''9' or 'A''F'
// (in ASCII code).
// Returns 1, if "hexdigit" is not a valid hex digit.
// Examples: HexToDec('3') returns 3;
// HexToDec('B') returns 11;
// HexToDec('X') returns 1;
{
int x = 1;
if ( ______________________________________________________ )
55

_________________________________________________;
else if ( ________________________________________________ )
_______________________________________________________;
return x;
}

Setting the Context

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

Practice and Application

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:

enum MAIL {FIRSTCLASS, PRIORITY};


double MailMeter(double ounces, MAIL type)
// Returns the required postage for a letter or package.
// "ounces" is the weight in ounces.
// "type" is the type of service: FIRSTCLASS or PRIORITY.

58

2.

Using the rules of short-circuit evaluation, correct the following statement to


prevent accessing elements of the array with subscripts out of bounds:
const int ROWS = 32, COLS = 32;
apmatrix<char> grid(ROWS, COLS);

if (grid[row1][col+1] == 'x' && row >= 1 && col < COLS1)

59

Lesson

Iterative Statements: while, for, do-while


Introduction
Iteration statements cause statements (or compound statements) to be executed zero or
more times, subject to some loop-termination criteria. When these statements are
compound statements, they are executed in order, except when either
the break statement or the continue statement is encountered. Loops repeat a statement
a certain number of times, or while a condition is fulfilled.
C++ provides three iteration statements while, do-while, for. Each of these iterates until
its termination expression evaluates to zero (false), or until loop termination is forced with
a break statement.

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

Activating Prior Knowledge

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

Setting the Context

Fill in the Blank


Directions:
1. Fill in the blanks in the following function that sets the elements of an array to the
integers 1 through n, where nis the length of the array:
void SetSequence (apvector<int> &v)

// Sets the elements of the vector v to


// consecutive integers, starting from 1.
{
61

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

2. double Polynomial(const apvector<double> &a, double x)


// Returns the value of the nth degree polynomial
// P(x) = a[0] + a[1]*x + a[2] * x^2 + ... + a[n] * x^n.
// Assumes that the length of a is n+1.
{
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
_____________________________________________________________
}

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

Practice and Application

Problem Solving

A non-negative big integer is represented as an array of N digits. The value of


each digit is an integer between 0 and 9. The most significant digits are at the
beginning of the array, and zero values indicate leading zeroes. Fill in the blanks
in the following function that calculates the sum of two big integers, a and b:
const int N = 100;
void Add(const apvector<int> &a, const apvector<int> &b,
apvector<int> &sum)
// Calculates the sum of two "big integers" a and b
// represented as arrays of digits. Places the result in the
// array sum.
// Assumes that the result fits into N digits: the overflow
// condition is ignored.
{
int i, d, carry = 0;
sum.resize(N);
for (____________________________________________________ ) {
d = a[i] + b[i] + carry;
sum[i] = _________________________________________;
carry = _______________________;
}
}

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.

2. Declarations must appear at the start of the body of a Java method.

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.

6. Whenever the "&&" operator is used, such as in:


exp1 && exp2
where exp1 and exp2 are boolean expressions, both the boolean expressions
are not always evaluated.

7. The expression (y >= z && a == b) is evaluated by first evaluating the expression


y >= z, and then evaluating a == b.

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

14. Objects of a super class can always be assigned to a subclass reference.

15. Objects of a subclass can be assigned to a super class reference.

16. When an instance of a class, or object, is specified as a parameter to a method, a


reference to the said object is passed to the method.

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.

22. Each method in a class must have a unique name.

23. Java does not allow a method with the same signature in a subclass, as a method
in the super class.

24. When a method or a variable in a class is declared as private, it can only be


accessed by the methods within the same class.

25. A method declaration must always contain the access level.

26. A method declared as final can be overridden by subclasses if it is also declared


as static.
68

27. A method declared as final can be overridden by subclasses if it is also declared


as static.

28. A method that is overridden in the subclass must retain the same return type and
parameter list.

29. The access level of an overridden method cannot be changed in a subclass.

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), (B), (C) & (E)


(A), (B) & (E)
(B), (D) & (E)
(B) & (E)
(D) & (E

6. Which of the following methods can be used to remove a java.awt.Component


object from the display?
a. delete()
b. remove()
c. disappear()
d. hide()
e. move()
7. The setBackground() method is part of the following class in java.awt package:
a. Graphics
b. Applet
c. Container
d. Object
e. Component
8. Which of the following strings can be used as mode strings for creating a
RandomAccessFile object?
70

(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

a. (C) & (E)


b. (A), (C) & (E)
c. (B),(C) & (D)
d. All of these.
23. Consider the following code:
class ClassA
a. Will compile and run successfully
b. Error. ClassB does not define a no-argument constructor
c. Error. There is no code in the class ClassB
d. Error. ClassA does not define a no-argument constructor
e. Error. There is no code in the constructor ClassA(int x)
24. A package is a collection of
a. classes
b. interfaces
c. editing tools
d. classes and interfaces
25. Which of the following statements are true?
(A) An abstract class may not have any final methods.
(B) A final class may not have any abstract methods.
(C) An inner class may be declared with any accessibility keyword.
(D) Transient variables must be static.
a. (A)
b. (A) & (C)
c. (D)
d. (B) & (C)
26. Which of the following defines a legal abstract class?
a. class Vehicle {<br>
abstract void display(); }
b. abstract Vehicle {<br>
abstract void display(); }
c. abstract class Vehicle {<br>
abstract void display(); }
d. class abstract Vehicle {<br>
abstract void display(); }
e. abstract class Vehicle {<br>
abstract void display(); {<br>
System.out.println("Car"); }}
27. Package p1 contains the following code:
package p1;
public class Student
a. Class result should be declared public.
b. Test class is not available.
74

c. Student class is not available.


d. Result body is not fully defined.
28. Consider the following code:
interface Area
a. Interface definition is incomplete
b. Method compute() in class Room should be declared public
c. Method compute() in interface Area should be declared public
d. All of these
29. The concept of multiple inheritance is implemented in Java by
(A) extending two or more classes
(B) extending one class and implementing one or more interfaces
(C) implementing two or more interfaces
(D) all of these
a. (B) & (C)
b. (A)
c. (A) & (C)
d. (D)
30. Which of the following expressions will produce errors upon compilation?
(A) boolean a = (boolean) 1;
(B) boolean b = (false && true);
(C) float y = 22.3;
a. (A)
b. (A), (C) & (D)
c. (A) & (C)
d. (A), (B) & (D
31. Which lines of the following will produce an error?
1. byte a1 = 2, a2 = 4, a3;
2. short s = 16;
3. a2 = s;
4. a3 = a1 * a2;
(The lines are numbered only for illustration in this question.)
a. Line 3 and Line 4
b. Line 1 only
c. Line 3 only
d. Line 4 only
e. Line 1 and Line 4
32. Examine the following code snippets to identify the legal loop constructs:
(A) for (int i = 22, int j = 0; i + j > 11; i = i-3, j++)
a. (A)
b. (A) & (D)
75

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

c. Error. Won't compile


d. XXX followed by YYY
44. What will be the output of the following program?
class Main2
a. XXX
b. XXX followed by YYY
c. YYY
d. Error. Won't compile
45. What is java_g used for?
a. Using the jdb tool
b. Executing a class with optimization turned off
c. To provide information about deprecated methods
d. None of these
46. With javadoc, which of the following denotes a javadoc comment?
a. //#
b. /**
c. /*
d. //**
47. Which of the following command lines options generates documentation for all
classes and methods?
a. -protected
b. -public
c. -verbose
d. -encoding
e. -private
48. Which javadoc tag is used to denote a comment for a method parameter?
a. @method
b. @parameter
c. @param
d. @argument
e. @value
49. Which of the following statements are valid array declaration?
(A) int number();
(B) float average[];
(C) double[] marks;
(D) counter int[];
a. (A)
b. (B) & (C)
c. (A) & (C)
d. (D)

78

50. Consider the following code


int number[] = new int[5]; After execution of this statement, which of the following
are true?
(A) number[0] is undefined
(B) number[5] is undefined
(C) number[4] is null
(D) number[2] is 0
(E) number.length() is 5
a. (A) & (E)
b. (C) & (E)
c. (B), (D) & (E)
d. (E)

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

System.out.println("a is " +a);


Answer: _______
12. State the output of the following code:
int a = 10;
int b = 5;
if(a > b)
{
if(b > 5)
System.out.println("b is " +b);
}
else
System.out.println("a is " +a);
Answer: _____________
13. What is the output of the following code:
int m = 100;
while(true)
{
if(m < 10)
break;
m = m - 10;
}
System.out.println("m is " +m);
Answer: _________
14. What is the output of the following code:
int m = 100;
while(true)
{
if(m < 10)
continue;
m = m - 10;
}
System.out.println("m is " +m);
Answer: ________________
15. Use a single line of code, complete the following class so that it returns x+y if the
value of x is equal to y, otherwise returns 0:
Public class XY
Answer: ____________________

81

Do it yourself
Directions:
1. Write a Java program to display Hello World on the screen.
Write your code here:

2. Write a Java program to display the asterisk pattern as shown below:


*****
*****
*****
*****
*****
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:

4. Write a Java program by using BufferedReader class to prompt a user to input


his/her name and then the output will be shown as an example below:
Hello Dara!
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:

6. Write Java program to generate a random number between 1 to 6.


To generate a random number, you can use the Random class of java.util
package. You may use the abs() method of Math class to make sure you can get
only a positive number.
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

Write your code here:

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.

Write your code here:

86

10. Write a Java program to determine whether an input number is an even number.
Write your code here:

11. Write a Java program that determines a students grade.


The program will read three types of scores(quiz, mid-term, and final scores) and
determine the grade based on the following rules:
-if the average score >=90% =>grade=A
-if the average score >= 70% and <90% => grade=B
-if the average score>=50% and <70% =>grade=C
-if the average score<50% =>grade=F
See the example output below:
Quiz score: 80
Mid-term score: 68
Final score: 90
Your grade is B.

87

Write your code here:

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

Write your code here:

13. Write a Java program by using two for loops to produce the output shown below:

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

89

Write your code here:

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

Activity 3: Decimal to Binary


6. 2 = 00000010
7. 7 = 00000111
8. 5 = 00000101
9. 8 = 00001000
10. 9 =00001001

6. 12 = 00001100
7. 15 = 00001111
8. 16 = 00010000
9. 20 = 00010100
10. 27 = 00011011

Activity 4: Binary to Decimal


6.
7.
8.
9.

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

Activity 7: Hexadecimal to Decimal


6. 00D5h =
7. 002Fh =
8. 0110h =
9. 0216h =
10. 004Bh =

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

Activity 3: Matching Type


Column A

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

Activity 4: Valid or Invalid


7. +32469 = V
8. +32767 = V
9. -32768 = V
10. +32785 = I
11. -32785 = I
12. +65535 = I
Activity 5: Positive or Negative

5.
6.
7.
8.

7FB9h = P
8123h = N
0D000h = N
649Fh = P

Activity 6: 16-bit Hexadecimal


5.
6.
7.
8.

-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

Activity 3: Supply the actual binary bits


Exponent (E)
2
5
0
-10
128
-1

Binary Representation
10000001
10000100
01111111
01110101
11111111
01111110

Activity 4: Supply the normalized value and resulting exponent


Binary Value
10000.11
1101.101
.00101
1.0001
10000011.0
.0000011001

Normalized As
1.000011
1.101101
1.01
1.0001
1.0000011
1.1001

Exponent
4
3
-3
0
7
-6

Activity 5: Supply the complete binary


Binary Value
-1.11
+1101.101
-.00101
+100111.0
+.0000001101011

Sign, Exponent, Mantissa


1 01111111 11000000000000000000000
0 10000010 10110100000000000000000
1 01111100 01000000000000000000000
0 10000100 00111000000000000000000
0 01111000 10101100000000000000000

Lesson 4.
Activity 1: Valid or Invalid
11. mov ax, bx = V

11. mov edx,ax = I

12. mov dx, bl = I

12. mov ax,es = V

13. mov ecx, edx = V

13. mov ax,16 = V

14. mov si,di = V

14. mov dx,7F65h = V

15. mov ds, ax = V

15. mov ecx, 6F23458h= V

16. mov ds,es = I

16. mov si, -1 = V

17. mov al, dh = V

17. mov ds, 1000h = I

18. mov ax,dh = I

18. mov al, 100h = I


95

19. mov ip,ax = I

19. mov 123, dh = I

10. mov si, cl = I

20. mov ss, ds = I

Activity 2: Valid or Invalid


Instruction
11. add ax, bx
12. add dx, bl
13. add ecx, dx
14. sub si, di
15. add bx, 90000
16. sub ds, 1
17. dec ip
18. dec edx
19. add edx, 1000h
20. sub ah, 126h

Valid or Invalid
V
I
I
V
I
I
I
V
V
I

Activity 3: Carry or No carry


8. mov ax, 0FFFFh
add ax, 1

CY

9. mov bh, 2
sub bh, 2

NC

10. mov dx, 0


dec dx
11. mov
al, 0DFh
add
al, 32h
12. mov
si, 0B9F6h
sub
si, 9874h
13. mov
cx, 695Fh
sub
cx, A218h

?? (Carry not affected by INC and DEC

CY

NC

CY

Activity 4: Zero or Not Zero

4. mov ax, 0FFFFh

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

Activity 5: Positive or Negative

4. mov ax, 0FFFFh


subax, 1

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

Activity 6: Carry, Sign, and Zero


4. mov
ax, 620h
sub
ah, 0F6h
5. mov
ax, 720h
sub
ax, 0E6h

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

Activity 2: Valid or Invalid


4. mov
eax, offset
byteVal
5. mov
dx, wordVal+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

14. move di, offset


98

wordVal
00000004h

Activity 4: Hexadecimal Value


4. mov
eax, offset
byteVal+2

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

Activity 5: Hexadecimal Value


4. mov
eax, offset
wordVal

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

Activity 6: Hexadecimal Value


4.
ax, dwordVal+2
I

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

Activity 2: Multiple Choice

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

Activity 3: Flash Card


1. o
2. 161
3. x = x<0?-x:x
4. n4 = 40; is unreachable
5. 200
6. six:33
7. null
8. s =
9. (i=10) is the problem
10. 10
11. a is 5
12. No output
13. m is 0
14. No output; Infinite loop
15. return(x == y)?x+y:0;

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.");

}
}

11. import java.util.*;


public class
JavaExercises
{
public static void
main(String[] args)
{
showGrade();
}
static void
showGrade(){
float quiz_score,

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(){

13. public class


JavaExercises
{
public static void
main(String[] args)
{
printStars();
}
static void
printStars(){

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");

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();
} while
(con.compareTo("y
")==0);
}catch(IOExceptio
n e){}

}
}

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.

Você também pode gostar