[go: up one dir, main page]

0% found this document useful (0 votes)
111 views70 pages

Past Paper Assignment

The document contains a collection of assembly language questions and answers, focusing on various topics such as data types, instructions, and program structure. It includes both short and long questions, with detailed explanations and example code for tasks like input validation and binary conversion. Additionally, it covers the instruction execution cycle, CPU bus connections, and the workings of specific assembly language instructions.

Uploaded by

ahmadhamza1402
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
111 views70 pages

Past Paper Assignment

The document contains a collection of assembly language questions and answers, focusing on various topics such as data types, instructions, and program structure. It includes both short and long questions, with detailed explanations and example code for tasks like input validation and binary conversion. Additionally, it covers the instruction execution cycle, CPU bus connections, and the workings of specific assembly language instructions.

Uploaded by

ahmadhamza1402
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

Name: Ayesha Tahir

Roll no. : 509


BS CS (Semester III) G-1
Assignment: Computer organization and Assembly Language.
TOPIC: PAST PAPERS
PAPER-1:

Short Questions:-
Q-1: Write an assembly language instruction to declare that can contain a number
not greater than 655535?
A-1: To declare a variable in assembly language that can contain a number not
greater than 65535, you need to use a WORD (16-bit) data type.
My Variable DW 65535
Q-2: Write an assembly language instruction to declare a variable which is big
enough to move to AL registers?
A-2: In x86 assembly, the AL register is an 8-bit register, so the variable
needs to be 1 byte in size. To declare such a variable, you would use the
BYTE directive:
My Byte Var DB 0xFF
Q-3: Write an assembly language instruction that take 2’s complement of
E230?
A-3: To take the 2's complement of a hexadecimal value like E230 in
assembly language, you can use the NEG instruction after loading the
value into a register. Here's how it can be done in x86 assembly:
mov ax, 0E230h ; Load the value E230h into AX register
neg ax ; Take the 2's complement of AX
Q-4: How does a logical address translated into a physical address in intel
8086?
A-4: The logical address of an instruction always consists of a CS (code
segment) and an IP (instruction pointer), shown in CS: IP format. The
physical address for the location of the instruction is generated by shifting
the CS left one hex digit and then adding it to the IP.
Q-5: Why do we use segment registers?
A-5: The segments provide address space protection and can be used for
shared memory. The architecture does not use explicit address-space
identifiers; the segment registers ensure address space protection.
Q-6: Write an assembly language instruction that clear all the bits of DL
registers?
A-6: To clear all the bits of the DL register in x86 assembly, you can use
the XOR instruction:
XOR DL, DL
The XOR instruction performs a bitwise XOR operation between DL and
itself. This is a common and efficient way to zero out registers in assembly
language.
Q-7: Suppose SP=0100; DI=0300; CX=0007. Assume Direction flag is set.
What would be the contents of SI, DI and CX after execution of instruction
LODSB twice?
A-7: If SP = 0100, DI = 0300, CX = 0007, and the Direction Flag (DF) is set:
Final Register Values:
SI = 00FE (decremented by 2 because DF is set and LODSB decrements
SI by 1 per execution).
DI = 0300 (unchanged, as LODSB does not affect DI).
CX = 0007 (unchanged, as LODSB does not affect CX).
Q-8: What is the difference between a Procedure and Macro? Which one is
more space efficient?
A-8: Difference between Procedure and Macro:
1. Definition:
Procedure: A block of code that is called using a CALL instruction and
returns with RET.
Macro: A preprocessor directive that replaces code inline during assembly.
2. Execution:
Procedure: Code is executed from a single memory location. Requires
additional instructions (CALL and RET).
Macro: Code is expanded inline, leading to faster execution but larger size.
3. Flexibility:
Procedure: Allows recursive calls and runtime decision-making.
Macro: Does not support recursion or runtime behavior as it is a
compile-time construct.
Space Efficiency: Procedures are more space-efficient because they reuse
the same block of code, whereas macros duplicate the code at every call
site, increasing memory usage.
Q-9: What is the purpose of EQU, OFFSET and .Data directives?
A-9: Purpose of Directives:
1. EQU:
Used to define constants.
Example: PI EQU 3.14 assigns PI the value 3.14.
2. OFFSET:
Used to get the memory address of a variable.
Example: MOV SI, OFFSET Var loads the address of Var into SI.
3. .DATA:
Marks the beginning of the data segment where variables and constants
are declared.
Example:
.DATA
Var DB 10
Defines Var in the data segment.
Q-10: Suppose SP=0200h; top of stack=012Ah. What are the contents of
IP and SP after RET instructions executed?
A-10: Initial State:
SP = 0200h
Top of Stack = 012Ah (assumes the value at address 0200h in memory is
012Ah).
RET Instruction:
1. RET pops the return address (IP) from the stack into the Instruction
Pointer (IP).
IP = [SP] = 012Ah
2. SP is incremented by 2 to point to the next value on the stack.
SP = SP + 2 = 0202h
Final State:
IP = 012Ah
SP = 0202h

LONG QUESTIONS:

QUESTION NO.1:
How will you perform the tasks by using either logical or shift instructions?
1- To clear the contents in AX register.
2- To multiply a signed value in DX register by 16.
3- To divide an unsigned value in CX register by 18.
4- To jump to a label “NEGATIVE” if AL contains a negative number.
ANSWER:
Solutions Using Logical or Shift Instructions:
1. To Clear the Content in AX Register:
Use the XOR instruction:
XOR AX, AX ; Clears AX by XORing it with itself
2. To Multiply a Signed Value in DX Register by 16:
Use the arithmetic left shift (SAL or SHL):
SHL DX, 4 ; Shifts the bits in DX left by 4 positions, multiplying by 16
3. To Divide an Unsigned Value in CX Register by 8:
Use the logical right shift (SHR):
SHR CX, 3 ; Shifts the bits in CX right by 3 positions, dividing by 8

4. To Jump to a Label "NEGATIVE" if AL Contains a Negative Number:


Check the most significant bit (sign bit) using the JS instruction:
JS NEGATIVE ; Jumps to the "NEGATIVE" label if the sign flag (SF) is set.
The JS instruction checks the sign flag, which is set if AL is negative (most
significant bit = 1).
QUESTION NO.2:

Write an assembly language program that prompt to the user to enter two binary
number of 4-bit length then display their sum in the next line in binary format. You
are required to implement proper checks so that only valid numbers can be input.
Below is a simple assembly program in x86 MASM syntax that prompts the user to
input two 4-bit binary numbers, checks for validity, and then displays their sum in
binary format.

Assembly Program

; x86 MASM Assembly Language Program


; This program reads two 4-bit binary numbers, validates them, and displays their
sum.

.data
prompt1 db "Enter the first 4-bit binary number (e.g., 1101): ", 0
prompt2 db "Enter the second 4-bit binary number (e.g., 1010): ", 0
invalid_input db "Invalid input! Only 4-bit binary numbers are allowed.", 10, 0
result_msg db "The sum in binary is: ", 0
input_buffer db 5, 0, 0, 0, 0, 0 ; Input buffer for 4-bit binary + null terminator
binary_table db 8, 4, 2, 1 ; Binary weights for conversion

.code
main PROC
; Print first prompt
lea dx, prompt1
mov ah, 09h
int 21h

; Get first input


lea dx, input_buffer
mov ah, 0Ah
int 21h

; Validate and convert first binary number


lea si, input_buffer + 2
call validate_and_convert
jc invalid_input_handler
mov bl, al ; Store first number in BL

; Print second prompt


lea dx, prompt2
mov ah, 09h
int 21h

; Get second input


lea dx, input_buffer
mov ah, 0Ah
int 21h

; Validate and convert second binary number


lea si, input_buffer + 2
call validate_and_convert
jc invalid_input_handler
mov bh, al ; Store second number in BH

; Add the two numbers


xor ax, ax
mov al, bl
add al, bh
; Print result message
lea dx, result_msg
mov ah, 09h
int 21h

; Convert result to binary and print


call print_binary

; Exit program
mov ah, 4Ch
int 21h

invalid_input_handler:
; Print invalid input message
lea dx, invalid_input
mov ah, 09h
int 21h
jmp main ; Restart the program

validate_and_convert PROC
; Validate and convert a 4-bit binary string to its decimal equivalent
; Input: SI -> Pointer to input string
; Output: AL -> Converted decimal value
; Flags: CF=1 on invalid input, CF=0 on success
xor al, al ; Clear AL (result accumulator)
xor cl, cl ; Clear CL (bit position)
validate_loop:
mov dl, [si]
cmp dl, 0
je validate_done ; End of string
inc si
cmp dl, '0'
jb invalid_input_error
cmp dl, '1'
ja invalid_input_error
shl al, 1 ; Shift AL left by 1 (multiply by 2)
or al, dl-'0' ; Add binary digit to AL
inc cl
cmp cl, 4
ja invalid_input_error ; More than 4 bits
jmp validate_loop
validate_done:
cmp cl, 4
jne invalid_input_error ; Less than 4 bits
clc ; Clear carry flag (valid input)
ret
invalid_input_error:
stc ; Set carry flag (invalid input)
ret
validate_and_convert ENDP

print_binary PROC
; Convert AL to binary and display it
; Input: AL -> Value to convert
; Uses: AX, BX, CX, DX
mov cx, 4 ; 4 bits to process
print_loop:
mov dl, al
and dl, 80h ; Isolate the highest bit
shr dl, 7 ; Shift it to the rightmost position
add dl, '0' ; Convert

QUESTION NO.3:
Write an assembly language program that input a number from keyboard in
decimal form and then display it in BCD form. Impose proper checks for valid input
and output.
Here is an assembly language program using x86 syntax that reads a decimal
number from the keyboard, validates it, and converts it to Binary-Coded Decimal
(BCD) form. The program assumes that the input is a single-digit number for
simplicity.
section .data
msg_input db "Enter a single-digit number (0-9): ", 0
msg_invalid db "Invalid input. Please enter a valid digit.", 0
msg_bcd db "BCD Representation: ", 0

section .bss
input resb 1
bcd resb 1

section .text
global _start

_start:
; Display input prompt
mov eax, 4 ; syscall: write
mov ebx, 1 ; file descriptor: stdout
mov ecx, msg_input ; message to display
mov edx, 36 ; message length
int 0x80

; Read input
mov eax, 3 ; syscall: read
mov ebx, 0 ; file descriptor: stdin
mov ecx, input ; buffer to store input
mov edx, 1 ; number of bytes to read
int 0x80
; Validate input
mov al, byte [input] ; load input character
cmp al, '0' ; check if input >= '0'
jl invalid_input
cmp al, '9' ; check if input <= '9'
jg invalid_input

; Convert to BCD
sub al, '0' ; convert ASCII to binary (subtract ASCII '0')
mov ah, 0 ; clear upper byte
mov byte [bcd], al ; store result in BCD buffer

; Display BCD representation


mov eax, 4 ; syscall: write
mov ebx, 1 ; file descriptor: stdout
mov ecx, msg_bcd ; message to display
mov edx, 21 ; message length
int 0x80

mov al, byte [bcd] ; load BCD value


add al, '0' ; convert binary to ASCII
mov [input], al ; store as ASCII for display
mov ecx, input ; buffer to display
mov edx, 1 ; length of one character
int 0x80

; Exit program
mov eax, 1 ; syscall: exit
xor ebx, ebx ; return code: 0
int 0x80

invalid_input:
; Display invalid input message
mov eax, 4 ; syscall: write
mov ebx, 1 ; file descriptor: stdout
mov ecx, msg_invalid ; message to display
mov edx, 40 ; message length
int 0x80

; Exit program
mov eax, 1 ; syscall: exit
xor ebx, ebx ; return code: 0
int 0x80

PAPER NO.2:
SHORT QUESTIONS:
Q-1: What are the three basic steps in instruction execution cycle?
A-1: The three basic steps in the instruction execution cycle are:
1. Fetch: Retrieve the instruction from memory.
2. Decode: Interpret the instruction to determine the required operation.
3. Execute: Perform the operation and store the result.
Q-2: The CPU is connected to the rest of the computer using what three buses?
A-2: The CPU is connected to the rest of the computer using three main buses:
1. Data Bus: Transfers data between the CPU and other components (e.g.,
memory, I/O devices).
2. Address Bus: Carries memory addresses to specify where data should be read
from or written to.
3. Control Bus: Sends control signals to coordinate operations (e.g., read/write
commands, interrupt signals).
Q-3: Is A5h is a valid hexadecimal constant?
A-3: Yes, A5h is a valid hexadecimal constant.
Q-4: What will be the result when we apply Shift Left on ‘1000000’?
A-4: When a Shift Left operation is applied to 1000000 (assuming a single-bit
shift):
Binary: 1000000 becomes 10000000.
Decimal: The value doubles, so 64 becomes 128.
Each left shift multiplies the number by 2.
Q-5: Name the four basic parts of an assembly language instruction.
A-5: The four basic parts of an assembly language instruction are:
1. Label: An optional identifier used as a reference point.
2. Mnemonic: Specifies the operation to perform (e.g., MOV, ADD).
3. Operands: The data or memory locations involved in the operation.
4. Comment: Optional explanation for clarity, starting with a comment symbol
(e.g.; in x86).
Q-6: How does the CALL instruction works?
A-6: The CALL instruction:
1. Pushes the return address onto the stack.
2. Jumps to the subroutine.
3. Resumes execution at the return address after the subroutine ends with a RET.
Q-7: What is the purpose of USES operator?
A-7: The USES operator in assembly language saves and restores specified
registers when entering and exiting a procedure, ensuring their values are
preserved for the calling code.
Q-8: What is the purpose of invoke directives?
A-8: The INVOKE directive in assembly language is used to call a procedure or
function, automatically handling the setup of parameters, pushing them onto the
stack, and managing the calling convention. It simplifies the process of calling
functions compared to manually managing registers and the stack.
Q-9: Which data type can hold a 32-bit signed integer?
A-9: The DWORD (Double Word) data type can hold a 32-bit signed integer.
Q-10: Write instructions that contains a loop to display 1 to 5 registers.
A-10: Here's an example of an assembly code that uses a loop to display the
numbers 1 to 5, assuming the use of x86 assembly and the int 0x80 syscall for
output:
Section .data
msg db 'Number: ', 0

section .bss
num resb 1

section .text
global _start

_start:
mov ecx, 1 ; Start with 1 (counter)

loop_start:
; Print "Number: "
mov eax, 4 ; syscall: write
mov ebx, 1 ; file descriptor: stdout
mov edx, 8 ; message length
mov ecx, msg
int 0x80

; Convert the number (ecx) to ASCII and print


add cl, '0' ; Convert to ASCII
mov [num], cl ; Store in num buffer
mov eax, 4 ; syscall: write
mov ebx, 1 ; file descriptor: stdout
mov ecx, num ; buffer containing the number
mov edx, 1 ; print 1 byte
int 0x80

; Check if counter <= 5, else exit


inc ecx
cmp ecx, 6
jl loop_start

; Exit program
mov eax, 1 ; syscall: exit
xor ebx, ebx ; return code: 0
int 0x80

LONG QUESTIONS:
QUESTION NO.1:
Write an assembly language program that reads a character from a keyboard and
determines whether the character is a vowel or consonant. Your program should
display proper message.
Below is an assembly language program written in 8086 assembly language that
reads a character from the keyboard and determines whether it is a vowel or
consonant. The program uses DOS interrupt services for input and output.

.model small
.stack 100h
.data
prompt db 'Enter a character: $'
vowel_msg db 'The character is a vowel.$'
consonant_msg db 'The character is a consonant.$'
invalid_msg db 'Invalid input. Please enter an alphabet.$'
input_char db 0
.code
main proc
mov ax, @data ; Initialize data segment
mov ds, ax

; Display prompt
lea dx, prompt
mov ah, 09h
int 21h

; Read character from keyboard


mov ah, 01h
int 21h
mov input_char, al ; Store input character

;
QUESTION NO.2:
Write an assembly language program that calculates the factorial on an integer
number.
Here is an example of an assembly language program in 8086 assembly language
that calculates the factorial of a given positive integer. The user provides the
input, and the program calculates and displays the factorial.

.model small
.stack 100h
.data
prompt db 'Enter a positive integer (0-12): $'
result_msg db 'Factorial: $'
input db 0
factorial dw 1
.code
main proc
mov ax, @data ; Initialize data segment
mov ds, ax

; Display prompt
lea dx, prompt
mov ah, 09h
int 21h

; Read character from keyboard


mov ah, 01h
int 21h
sub al, '0' ; Convert ASCII to integer
mov input, al

; Validate input (0-12)


cmp al, 0
jl invalid_input ; If input < 0, invalid
cmp al, 12
jg invalid_input ; If input > 12, invalid

; Calculate factorial
mov cx, input ; Store input in CX for loop counter
cmp cx, 0
je display_result ; If input is 0, factorial is 1

factorial_loop:
mov ax, factorial
mul cx ; Multiply AX by CX
mov factorial, ax ; Store result in factorial
loop factorial_loop ; Decrement CX and repeat

display_result:
; Display result message
lea dx, result_msg
mov ah, 09h
int 21h

; Convert factorial to string and display


mov ax, factorial
call print_number
; Exit program
mov ah, 4Ch
int 21h

invalid_input:
; Display error message
lea dx, prompt
mov ah, 09h
int 21h
jmp main

; Subroutine to print number in AX


print_number proc
push ax ; Save AX
push bx
push cx
push dx

mov cx, 10 ; Divisor for decimal system


xor dx, dx ; Clear DX (high word of dividend)

convert_loop:
div cx ; Divide AX by 10, quotient in AX, remainder in DX
push dx ; Push remainder (digit) onto stack
add dl, '0' ; Convert to ASCII
cmp ax, 0 ; Check if quotient is 0
jne convert_loop ; If not, continue

print_digits:
pop dx ; Pop digit from stack
mov ah, 02h ; DOS interrupt for single character output
int 21h
cmp sp, bp ; Check if stack is empty
jne print_digits

pop dx
pop cx
pop bx
pop ax
ret
print_number endp
main endp
end main
QUESTION NO.3:
Write an assembly language program that alphabetically sorts an array of ten
characters.
Below is an assembly language program in 8086 that alphabetically sorts an array
of 10 characters using the Bubble Sort algorithm:
.model small
.stack 100h
.data
prompt db 'Unsorted array: $'
sorted_msg db 'Sorted array: $'
array db 'HELLOWORLD' ; Array to be sorted
array_len dw 10 ; Length of the array
newline db 0Dh, 0Ah, '$' ; Newline

.code
main proc
mov ax, @data ; Initialize data segment
mov ds, ax

; Display the unsorted array


lea dx, prompt
mov ah, 09h
int 21h

lea dx, array


mov ah, 09h
int 21h

; Perform sorting
lea si, array ; Load the starting address of the array
mov cx, array_len ; Set the outer loop counter (number of passes)

outer_loop:
dec cx ; Decrease outer loop counter
mov bx, cx ; Set inner loop counter
mov si, offset array ; Reset SI to the start of the array

inner_loop:
mov al, [si] ; Load current element
mov ah, [si+1] ; Load next element
cmp al, ah ; Compare current and next element
jbe no_swap ; If in order, skip swapping

; Swap elements
mov [si], ah ; Move next element to current
mov [si+1], al ; Move current element to next

no_swap:
inc si ; Move to the next element
dec bx ; Decrease inner loop counter
jnz inner_loop ; Repeat inner loop if BX > 0

cmp cx, 1 ; Check if the outer loop is complete


jg outer_loop ; Repeat outer loop if CX > 1

; Display the sorted array


lea dx, newline
mov ah, 09h
int 21h

lea dx, sorted_msg


mov ah, 09h
int 21h

lea dx, array


mov ah, 09h
int 21h

; Exit program
mov ah, 4Ch
int 21h

main endp
end main
PAST PAPER 3:
SHORT QUESTIONS:
Q-1: Name the four basic parts of an assembly language instructions?
A-1: The four basic parts of an assembly language instruction are:
1. Label (optional)
2. Opcode (operation to perform)
3. Operands (data or addresses)
4. Comment (optional explanation)
Q-2: What is the difference between PROC and MACRO?
A-2: The difference between PROC and MACRO in assembly language:
1. PROC (Procedure):
Defines a reusable block of code (subroutine).
Requires a call and return mechanism.
Uses memory and allows recursion.
2. MACRO:
Defines a reusable code template.
Expanded inline during assembly (no call/return).
Faster but increases code size.
Q-3: What are the different memory addressing techniques used in intel
architecture?
A-3: Intel x86 architecture employs several memory addressing modes to access
data:
1. Immediate Addressing: The operand is a constant value embedded directly
within the instruction.
Example: MOV AX, 5
2. Register Addressing: The operand resides in a register.
Example: MOV AX, BX
3. Direct Addressing: The instruction specifies the memory address of the
operand.
Example: MOV AX, [1234H]
4. Indirect Addressing: A register contains the memory address of the operand.
Example: MOV AX, [BX]
5. Indexed Addressing: Combines a base address with an index to calculate the
effective memory address.
Example: MOV AX, [SI + 4]
6. Base-Indexed Addressing: Utilizes both a base register and an index register to
determine the memory address.
Example: MOV AX, [BX + SI]
7. Base-Indexed with Displacement: Incorporates a base register, an index register,
and a displacement value to compute the memory address.
Example: MOV AX, [BX + SI + 8]
These addressing modes provide flexibility in accessing memory, enabling efficient
data manipulation and control flow within programs.
Q-4: Describe the function of the following terms:
A-4: i- DUP operator:
In assembly language, the DUP operator is used during data definition to allocate
and initialize storage by duplicating a specified value multiple times. It is
particularly useful for creating arrays or reserving blocks of memory with a
consistent initial value.
Syntax:
count DUP (initialvalue)
count: Specifies the number of times to duplicate the initial value.
initialvalue: The value to be duplicated; can be a constant, an expression, or a
sequence of values.
Examples:
1. Allocating an array of zeros:
array1 BYTE 20 DUP(0)
This line allocates 20 bytes of memory, each initialized to 0.
2. Allocating uninitialized storage:
buffer BYTE 50 DUP(?)
This reserves 50 bytes of uninitialized memory, where ? indicates that the initial
value is unspecified.
3. Creating a repeated string pattern:
pattern BYTE 4 DUP("AB")
This allocates 8 bytes of memory containing the sequence "ABABABAB".
The DUP operator is evaluated at assembly time, meaning it does not generate
runtime instructions but rather directs the assembler to allocate and initialize
memory as specified.
This operator enhances code readability and efficiency by simplifying the
declaration of repetitive data structures.
ii- EQU OPERATOR:
In assembly language, the EQU directive assigns a symbolic name to a constant
value or expression, enhancing code readability and maintainability. Unlike
variables, symbols defined with EQU do not consume memory; they are evaluated
at assembly time and replaced with their corresponding values during code
generation.

Syntax:
symbol EQU expression
symbol: The name representing the constant.
expression: A constant value or an expression that evaluates to a constant.
Examples:
1. Defining a constant value:
MAX_LENGTH EQU 100
Here, MAX_LENGTH is defined as 100.
2. Using the constant in instructions:
MOV CX, MAX_LENGTH ; Set CX register to 100
The assembler replaces MAX_LENGTH with 100 during assembly.
3. Defining a symbolic name for an address:
BUFFER_START EQU 0x2000
BUFFER_START now represents the memory address 0x2000.
4. Using the symbolic address:
MOV AX, [BUFFER_START] ; Load value from address 0x2000 into AX
The assembler substitutes BUFFER_START with 0x2000.
III - TEXTEQU operator:
In assembly language, the TEXTEQU directive assigns a symbolic name to a text
string or expression, facilitating code readability and maintenance. Unlike the EQU
directive, which can define numeric or text constants, TEXTEQU is specifically
designed for text substitutions.

Syntax:

name TEXTEQU textitem


name: The symbolic identifier to be defined.

textitem: A literal string, a constant preceded by %, or the string returned by a


macro function.

Example:

HELLO_MSG TEXTEQU <"Hello, World!">

In this example, HELLO_MSG is defined as the text string "Hello, World!".


Subsequent references to HELLO_MSG in the code will be replaced with this string
during assembly.

Key Points:

Text Substitution: TEXTEQU facilitates the creation of aliases for text strings or
expressions, enhancing code clarity.

Assembly-Time Evaluation: The substitution occurs during assembly, not at


runtime, ensuring efficient code generation.

Immutability: Once defined, the symbolic name cannot be redefined later in the
code.
By using TEXTEQU, developers can manage repetitive text strings more effectively,
leading to cleaner and more maintainable assembly code.

For a more in-depth understanding, you can refer to the official Microsoft
documentation on TEXTEQU.

LONG QUESTIONS:
QUESTION NO.1:
Write a procedure that reads a text-paragraph from a file and then prints the
number of character on the screen.
To create an assembly procedure that reads a text paragraph from a file and prints
the number of characters on the screen, you can follow these steps:

1. Open the File: Use the DOS interrupt 0x21 with function 0x3D to open the file in
read mode.

2. Read the File: Use the DOS interrupt 0x21 with function 0x3F to read the file's
contents into a buffer.

3. Count Characters: Iterate through the buffer, counting each character until you
reach the end of the file.

4. Display the Count: Convert the count to a string and display it using the DOS
interrupt 0x21 with function 0x09.
Here's an example implementation in x86 assembly:

.model small
.stack 100h

.data
filename db 'example.txt', 0
buffer db 256 dup(0)
count db 0

.code
main:
; Initialize data segment
mov ax, @data
mov ds, ax

; Open the file


mov ah, 3Dh ; DOS function: open file
mov al, 0 ; Read mode
lea dx, filename ; Address of filename
int 21h ; Call DOS interrupt
jc open_error ; Jump if carry flag is set (error)
mov bx, ax ; File handle

; Read the file


mov ah, 3Fh ; DOS function: read file
lea dx, buffer ; Address of buffer
mov cx, 256 ; Number of bytes to read
int 21h ; Call DOS interrupt
mov si, ax ; Number of bytes read

; Count characters
xor ax, ax ; Clear AX register (counter)
count_loop:
cmp si, 0 ; Check if all bytes are read
je done_counting
inc ax ; Increment counter
dec si ; Decrement bytes remaining
jmp count_loop
done_counting:

; Convert count to string


lea di, buffer ; Address of buffer
add di, 256 ; Move to end of buffer
mov byte ptr [di], '$' ; Null-terminate the string
dec di
mov cx, 10 ; Base 10
mov bx, ax ; Copy count to BX
call itoa ; Convert integer to ASCII

; Display the count


lea dx, buffer ; Address of buffer
mov ah, 9 ; DOS function: display string
int 21h ; Call DOS interrupt

; Close the file


mov ah, 3Eh ; DOS function: close file
mov bx, bx ; File handle
int 21h ; Call DOS interrupt

; Exit program
mov ah, 4Ch ; DOS function: terminate program
int 21h ; Call DOS interrupt

open_error:
; Handle file open error
; (e.g., display error message)
; ...
; Exit program
mov ah, 4Ch ; DOS function: terminate program
int 21h ; Call DOS interrupt

itoa:
; Convert integer in BX to ASCII string at DI
; Assumes DI points to end of buffer
; Assumes CX is base (e.g., 10 for decimal)
; Returns DI pointing to beginning of string
; ...
ret

Explanation:

The itoa procedure is a placeholder for a function that converts an integer to its
ASCII string representation.

The buffer is used to store the file's contents temporarily.

The count variable stores the number of characters read.

This example demonstrates how to read a file, count its characters, and display
the count using DOS interrupts in x86 assembly.
QUESTION NO.2:
Write a program that inputs 10 digit. - - - - - - - - - - - - - - - - - - - - can be input.
To create an assembly program that inputs 10 digits, stores them in an array, and
finds the minimum digit with input validation to ensure only digits are entered,
you can follow these steps:

1. Initialize Data Segment: Define the array to store the digits and a variable to
hold the minimum digit.

2. Input Loop: Prompt the user to enter a digit, validate the input to ensure it's a
digit, and store it in the array.

3. Find Minimum Digit: Iterate through the array to find the minimum digit.

4. Display Result: Convert the minimum digit to its ASCII representation and
display it.

Here's an example implementation in x86 assembly:

.model small
.stack 100h
.data
prompt db 'Enter a digit (0-9): $'
newline db 0Ah, 0Dh, '$'
digits db 10 dup(0) ; Array to store 10 digits
min_digit db 0

.code
main:
; Initialize data segment
mov ax, @data
mov ds, ax

; Input loop
lea dx, prompt
mov ah, 9
int 21h ; Display prompt

lea si, digits ; SI points to the digits array


mov cx, 10 ; Loop counter for 10 digits

input_loop:
; Read a character
mov ah, 1
int 21h
sub al, '0' ; Convert ASCII to integer

; Validate input (check if it's a digit)


cmp al, 0
jl invalid_input
cmp al, 9
jg invalid_input

; Store the digit in the array


mov [si], al
inc si

loop input_loop
jmp find_min

invalid_input:
; Handle invalid input (e.g., display error message)
lea dx, newline
mov ah, 9
int 21h ; Display newline
lea dx, prompt
mov ah, 9
int 21h ; Display prompt again
jmp input_loop

find_min:
; Initialize min_digit with the first digit
lea si, digits
mov al, [si]
mov [min_digit], al
inc si

; Find the minimum digit


mov cx, 9 ; 9 comparisons remaining
find_min_loop:
mov al, [si]
cmp al, [min_digit]
jge next_digit
mov [min_digit], al
next_digit:
inc si
loop find_min_loop

; Display the minimum digit


lea dx, newline
mov ah, 9
int 21h ; Display newline
lea dx, min_digit
mov ah, 9
int 21h ; Display minimum digit

; Exit program
mov ah, 4Ch
int 21h

Explanation:

Data Segment: Defines the prompt message, newline characters, an array to store
the digits, and a variable to hold the minimum digit.

Input Loop: Prompts the user to enter a digit, reads the input, converts it from
ASCII to integer, validates that it's a digit, and stores it in the array. If the input is
invalid, it prompts the user again.

Find Minimum Digit: Initializes the min_digit variable with the first digit and
iterates through the array to find the minimum digit.

Display Result: Displays the newline and the minimum digit.

Note: This program assumes the use of DOS interrupts for input and output. The
input validation checks if the entered character is between '0' and '9' (ASCII values
48 to 57). If the input is invalid, it prompts the user again.
QUESTION NO.3:
Write a program that should input two single digit numbers - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - and display results.
o create an assembly program that inputs two single-digit numbers, performs an
arithmetic operation based on user choice, and displays the result, you can follow
these steps:

1. Initialize Data Segment: Define variables to store the two digits, the result, and
a prompt message.

2. Input First Digit: Prompt the user to enter the first digit and store it in a variable.

3. Input Second Digit: Prompt the user to enter the second digit and store it in
another variable.

4. Choose Operation: Prompt the user to choose an arithmetic operation


(addition, subtraction, multiplication, or division).

5. Perform Operation: Based on the user's choice, perform the corresponding


arithmetic operation.
6. Display Result: Convert the result to its ASCII representation and display it.

Here's an example implementation in x86 assembly:

.model small
.stack 100h

.data
prompt1 db 'Enter first digit (0-9): $'
prompt2 db 'Enter second digit (0-9): $'
prompt3 db 'Choose operation: 1=Add, 2=Sub, 3=Mul, 4=Div: $'
result_msg db 'Result: $'
newline db 0Ah, 0Dh, '$'
digit1 db 0
digit2 db 0
result db 0

.code
main:
; Initialize data segment
mov ax, @data
mov ds, ax
; Input first digit
lea dx, prompt1
mov ah, 9
int 21h ; Display prompt1
lea dx, digit1
mov ah, 0Ah
int 21h ; Read first digit

; Input second digit


lea dx, prompt2
mov ah, 9
int 21h ; Display prompt2
lea dx, digit2
mov ah, 0Ah
int 21h ; Read second digit

; Input operation choice


lea dx, prompt3
mov ah, 9
int 21h ; Display prompt3
lea dx, result
mov ah, 0Ah
int 21h ; Read operation choice
; Convert ASCII digits to integers
lea si, digit1
mov al, [si+1]
sub al, '0'
mov bl, al ; Store first digit in bl

lea si, digit2


mov al, [si+1]
sub al, '0'
mov bh, al ; Store second digit in bh

; Perform operation based on user choice


lea si, result
mov al, [si+1]
sub al, '0'
cmp al, 1
je add_digits
cmp al, 2
je sub_digits
cmp al, 3
je mul_digits
cmp al, 4
je div_digits
jmp invalid_choice

add_digits:
add bl, bh
jmp display_result

sub_digits:
sub bl, bh
jmp display_result

mul_digits:
imul bl, bh
jmp display_result

div_digits:
xor dx, dx
div bh
jmp display_result

invalid_choice:
; Handle invalid choice (e.g., display error message)
lea dx, newline
mov ah, 9
int 21h ; Display newline
lea dx, result_msg
mov ah, 9
int 21h ; Display error message
jmp main

display_result:
; Convert result to ASCII
add bl, '0'
lea dx, result
mov [dx+1], bl
lea dx, result_msg
mov ah, 9
int 21h ; Display result message
lea dx, result
mov ah, 9
int 21h ; Display result
lea dx, newline
mov ah, 9
int 21h ; Display newline

; Exit program
mov ah, 4Ch
int 21h
Explanation:

Data Segment: Defines prompt messages, a result message, newline characters,


variables to store the two digits, and a variable to store the result.

Input First Digit: Prompts the user to enter the first digit and stores it in the digit1
variable.

Input Second Digit: Prompts the user to enter the second digit and stores it in the
digit2 variable.

Input Operation Choice: Prompts the user to choose an arithmetic operation and
stores the choice in the result variable.

Convert ASCII to Integer: Converts the ASCII values of the input digits to their
corresponding integer values.

Perform Operation: Performs the arithmetic operation based on the user's choice:
addition, subtraction, multiplication, or division.

Display Result: Converts the result to its ASCII representation and displays it.

PAST PAPER 4:

SHORT QUESTIONS:

Q-1:Assume DL contains the ASCII code - - - - - - - - - - - - - - - - - - - - - - - for


conversion)?
A-1: To convert a lowercase letter (ASCII code) in DL to uppercase using logic
instructions, subtract 32 from the ASCII value since the difference between
lowercase and uppercase letters in ASCII is 32. Here's a short assembly-like
approach:
SUB DL, 32; Convert lowercase to uppercase
Explanation:
Subtracting 32 adjusts the ASCII value from the lowercase range ('a' to 'z', 97–122)
to the uppercase range ('A' to 'Z', 65–90).
Printing (example using INT 21h in x86 assembly):
MOV AH, 02h; Function to print a character
MOV DL, <converted ASCII value>
INT 21h ; Print the character
Q-2:Assume the following - - - - - - - - - - - - - - - - - - - - - - - - - - to variable C.
A-2:
Q-3:A memory location has physical - - - - - - - - - - - - - - - - - - - - - - - - - in this
segment.
A-3: 1. Segment Address:
2. Maximum Physical Address in this Segment: 9FFFFh
Q: Assume SI=0100, DI=0200, CX=0005. - - - - - - - - - - - - - - - - - - - - - - twice?
A-3: The CMPSW instruction compares words (16-bit) at addresses pointed to by
SI (source index) and DI (destination index). When the Direction Flag (DF) is set, SI
and DI decrement after each operation. Each decrement is by 2 (word size). Here's
the step-by-step update:
Initial values:
SI = 0100
DI = 0200
CX = 0005
After first CMPSW execution:
SI = 0100 - 2 = 00FE
DI = 0200 - 2 = 01FE
CX = 0005 - 1 = 0004
After second CMPSW execution:
SI = 00FE - 2 = 00FC
DI = 01FE - 2 = 01FC
CX = 0004 - 1 = 0003
Final values:
SI = 00FC
DI = 01FC
CX = 0003
LONG QUESTIONS:
Q-1:Write an assembly language program that prompts the user - - - - - - - - - - - - - -
- - - - - - - not a substring?
A-2: Here is an assembly language program written in x86 assembly using MASM
(Microsoft Macro Assembler) that checks if the second string is a substring of the
first:

Program Code

.DATA
prompt1 db "Enter first string: ", 0
prompt2 db "Enter second string: ", 0
yesMsg db "Yes, it is a substring.", 0
noMsg db "Not a substring.", 0
str1 db 100 dup(0) ; Space to store the first string
str2 db 100 dup(0) ; Space to store the second string

.CODE
main PROC
; Prompt user to enter the first string
lea dx, prompt1
mov ah, 09h
int 21h

lea dx, str1


mov ah, 0Ah
int 21h

; Prompt user to enter the second string


lea dx, prompt2
mov ah, 09h
int 21h

lea dx, str2


mov ah, 0Ah
int 21h
; Find if str2 is a substring of str1
lea si, str1 + 2 ; Skip the length byte in the input buffer
lea di, str2 + 2 ; Skip the length byte in the input buffer

call isSubstring

cmp ax, 1 ; Check the return value


je substringFound

; If not a substring
lea dx, noMsg
mov ah, 09h
int 21h
jmp exit

substringFound:
; If it is a substring
lea dx, yesMsg
mov ah, 09h
int 21h

exit:
mov ah, 4Ch
int 21h
main ENDP

isSubstring PROC
; Inputs: SI = address of str1, DI = address of str2
; Output: AX = 1 if str2 is a substring of str1, else 0
push si
push di

nextChar:
mov cx, 0 ; Reset counter
mov bx, di ; Save DI position
mov dx, si ; Save SI position

compareChars:
mov al, [si] ; Get char from str1
cmp al, 0 ; Check for end of string
je notSubstring ; If end of str1, no match

cmp al, [di] ; Compare with char from str2


jne skipToNext ; If not matching, skip further comparison

inc si ; Move to next char in str1


inc di ; Move to next char in str2
inc cx ; Increment counter

mov al, [di] ; Check if end of str2


cmp al, 0
je foundSubstring ; If end of str2, it’s a match
jmp compareChars

skipToNext:
inc dx ; Move SI to next position
mov si, dx
lea di, bx ; Reset DI
jmp nextChar

foundSubstring:
mov ax, 1 ; Return 1 for substring found
pop di
pop si
ret

notSubstring:
mov ax, 0 ; Return 0 for not a substring
pop di
pop si
ret
isSubstring ENDP

END main
Q-2: a)Write down the note on all string instructions and also explain them - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - of examples?
b)Write down the name of different - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - are used?
A-3:a) In x86 assembly language, string instructions are specialized instructions
designed to operate on strings of bytes, words, or doublewords. These
instructions often work in conjunction with the EAX, ESI, EDI, and ECX registers to
efficiently process blocks of memory.

---

String Instructions Overview

1. MOVSB, MOVSW, MOVSD

Description: Moves data from the source memory location to the destination
memory location.

Operands:

Source: Address in DS:ESI.


Destination: Address in ES:EDI.

Variants:

MOVSB - Moves a byte.

MOVSW - Moves a word (2 bytes).

MOVSD - Moves a doubleword (4 bytes).

Example:

lea esi, src ; Load source address


lea edi, dest ; Load destination address
mov ecx, 5 ; Number of bytes to copy
rep movsb ; Copy 5 bytes from [esi] to [edi]
---

2. CMPSB, CMPSW, CMPSD

Description: Compares the source string at DS:ESI with the destination string at
ES:EDI.

Flags Affected: Updates ZF, CF, and SF based on the comparison.

Variants:

CMPSB - Compares bytes.

CMPSW - Compares words.


b) In x86 architecture, there are several registers, each serving specific purposes.
These registers are broadly categorized into general-purpose, segment,
index/pointer, and control registers. Here's a detailed explanation of the different
types of registers and their purposes:

---

General-Purpose Registers

These registers are used for arithmetic, data manipulation, and addressing.
1. EAX (Accumulator Register)

Primary register for arithmetic and logical operations.

Used for input/output operations and multiplication/division instructions.

Example:

mov eax, 10 ; Load 10 into EAX


add eax, 5 ; Add 5 to EAX

2. EBX (Base Register)

Often used as a pointer to data in memory.

Can also serve general arithmetic purposes.

Example:

mov ebx, array ; EBX points to the start of the array


3. ECX (Counter Register)

Used as a loop counter and in string instructions.

Implicitly used by LOOP and REP instructions.

Example:

mov ecx, 5 ; Set loop count to 5


loop_start:
; Do something
loop loop_start

4. EDX (Data Register)

Used in input/output operations, multiplication, and division.

Holds the remainder in division operations.

Example:
mov eax, 10
mov ebx, 3
div ebx ; EAX = quotient, EDX = remainder

5. ESI (Source Index Register)

Points to the source in string operations.

Often used for memory addressing.

Example:

lea esi, src_string ; Load address of source string

6. EDI (Destination Index Register)

Points to the destination in string operations.

Often used for memory addressing.


Example:

lea edi, dest_string ; Load address of destination string

7. EBP (Base Pointer)

Points to the base of the stack frame in function calls.

Helps access function parameters and local variables.

Example:

mov ebp, esp ; Set up stack frame

8. ESP (Stack Pointer)

Points to the top of the stack.

Automatically updated during PUSH and POP instructions.


Example:

push eax ; Decrease ESP and store EAX


pop ebx ; Increase ESP and load into EBX

---

Segment Registers

These registers are used to hold segment addresses in memory.

1. CS (Code Segment)

Points to the segment containing the currently executing code.

Example: Used internally for instruction fetch.

2. DS (Data Segment)
Points to the segment containing data.

Example:

mov ax, ds:[array] ; Access data in DS segment

3. SS (Stack Segment)

Points to the segment containing the stack.

Works with ESP and EBP.

4. ES, FS, GS

Additional segment registers for specialized memory addressing.


---

Control Registers

Used for system-level tasks, such as memory management.

1. EIP (Instruction Pointer)

Points to the address of the next instruction to be executed.

Automatically updated after each instruction.

2. EFLAGS

Stores status flags, control flags, and system flags.

Key Flags:

ZF (Zero Flag): Set if the result of an operation is zero.

CF (Carry Flag): Set if an arithmetic operation generates a carry/borrow.


SF (Sign Flag): Indicates the sign of the result.

OF (Overflow Flag): Set if an arithmetic operation causes an overflow.

---

Floating-Point Registers

Used in floating-point arithmetic operations.

1. ST0–ST7

Registers in the x87 FPU stack.

Used for floating-point calculations.


---

Purpose Summary

This comprehensive understanding helps programmers and system developers


efficiently use registers for optimized coding and debugging.

You might also like