CENG 103
Introduction to Computer Engineering
Part V – Software and Programming
Prof. Dr. Semih Bilgen
Istanbul Okan University
Introduction to programming
• A program is a collection of computer instructions, to be executed
one after another, to achieve a certain goal – to «solve a problem».
• Instructions are executed in the sequence they are stored in memory,
unless a control instructions changes that order.
• «Structured Programming» restricts how control instructions may
change execution order. The «legal» structures are:
• Sequence
• Conditional execution («if condition holds, then do this, else do that»…)
• Loop («repeat the sequence of instructions while/until condition holds»…)
Fundamental constructs of structured programming
e.g. Multiplication of two integers by repeated addition
Assume that location x3007, abbreviated M[x3007],
contains the value 5, and M[x3008] contains the
value 4.
We start by copying the two values from memory
to the two registers R1 and R2.
We are going to accumulate the results of the
additions in R3, so we initialize R3 to 0.
Then we add 5 to R3 and subtract 1 from R2 so we
will know how many more times we will need to
add 5 to R3.
We keep doing this (adding 5 to R3 and subtracting
1 from R2) until R2 contains the value 0. That tells
us that we have added 5 to R3 four times and we
are done, so we HALT the computer. R3 contains
the value 20, the result of our multiplication.
e.g. LC-3 code to multiply 5 x 4 by repeated addition
Important exercise: Study examples in Sec. 6.2, Patt&Patel, on debugging a program)!
e.g. Multiply two integers
Address 15 1 13 12 11 10 9 8 7 6 5 4 3 2 1 0 Instruction
4
X3200 0 1 0 1 0 1 0 0 1 0 1 0 0 0 0 0 R2 0
X3201 0 0 0 1 0 1 0 0 1 0 0 0 0 1 0 0 R2 R2 + R4
X3202 0 0 0 1 1 0 1 1 0 1 1 1 1 1 1 1 R5 R5 - 1
X3203 0 0 0 0 0 1 1 1 1 1 1 1 1 1 0 1 BR zp x3201
x3204 1 1 1 1 0 0 0 0 0 0 1 0 0 1 0 1 HALT
The integers to be multiplied are already loaded into R4 and R5.
The result will be stored in R2.
Does this program work correctly? E.g. Does it halt with R2 = 10 when it is run with R4 = 5 and R5 = 2?
e.g. Multiply 5 x 2 – debugging
Address 15 1 13 12 11 10 9 8 7 6 5 4 3 2 1 0 Instruction
4
X3200 0 1 0 1 0 1 0 0 1 0 1 0 0 0 0 0 R2 0
X3201 0 0 0 1 0 1 0 0 1 0 0 0 0 1 0 0 R2 R2 + R4
X3202 0 0 0 1 1 0 1 1 0 1 1 1 1 1 1 1 R5 R5 - 1
X3203 0 0 0 0 0 1 1 1 1 1 1 1 1 1 0 1 BR zp x3201
x3204 1 1 1 1 0 0 0 0 0 0 1 0 0 1 0 1 HALT
The loop is executed not 2 but three times, resulting in 15, instead of 10 in R2. (FAULT)
The BUG is that in the BRANCH statement, the condition code is written as zp (branch if zero or positive)
which causes one more execution of the loop after the correct result is obtained.
The BRANCH must be done only if the last loaded value is positive (not when it is zero). (CORRECTION)
So, the correct instruction at address x3203 must be:
x3203 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 1 BR p x3201