Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

SSrecord Merged

Download as pdf or txt
Download as pdf or txt
You are on page 1of 193

1

PROGRAM
FCFS
#include <stdio.h>
void main() {
int n, at[20], bt[20], wt[20], tat[20], p[20], ct[20], i, j, temp;
float ttat = 0, twt = 0;
printf("Enter how many processes:\n");
scanf("%d", &n);
printf("Enter arrival time:\n");
for(i = 0; i < n; i++) {
scanf("%d", &at[i]);
p[i] = i + 1;
}
printf("Enter burst time:\n");
for(i = 0; i < n; i++) {
scanf("%d", &bt[i]);
}
for(i = 0; i < n - 1; i++) {
for(j = 0; j < n - i - 1; j++) {
if(at[j] > at[j + 1])
{ temp = at[j];
at[j] = at[j + 1];
at[j + 1] = temp;
temp = bt[j];
bt[j] = bt[j + 1];
bt[j + 1] = temp;
temp = p[j];
p[j] = p[j + 1];
p[j + 1] = temp;
}
}

2
DATE:29/07/2024

EXPERIMENT NO.1
CPU SCHEDULING ALGORITHMS

AIM: Simulate the following CPU Scheduling Algorithms to find turnaround time and average time
1)FCFS 2) SJF 3) Round Robin
ALGORITHM: FCFS
1. Start
2. Input the number of processes n, and for each process, input its arrival time at[] and burst time bt[].
3. Assign Process IDs as 1 to n.
4. Sort the processes by arrival time using Bubble Sort, swapping the arrival time (at[]), burst time (bt[]),
and process ID (p[]).
5. Calculate Completion Time (ct[]):
a. For the first process, set ct[0] = at[0] + bt[0].
b. For each remaining process, if it arrives after the previous one finishes, update ct[i] = at[i] + bt[i];
otherwise, ct[i] = ct[i-1] + bt[i].
6. Calculate Turnaround Time (tat[]) as tat[i] = ct[i] - at[i].
7. Calculate Waiting Time (wt[]) as wt[i] = tat[i] - bt[i].
8. Calculate Averages for turnaround time and waiting time.
9. Display the results for each process and the average times.

10. Stop.

3
}
ct[0] = at[0] + bt[0];
for(i = 1; i < n; i++) {
if(ct[i - 1] < at[i]) {
ct[i] = at[i] + bt[i];
} else {
ct[i] = ct[i - 1] + bt[i];
}
}
for(i = 0; i < n; i++)
{ tat[i] = ct[i] - at[i];
wt[i] = tat[i] - bt[i];
ttat += tat[i];
twt += wt[i];
}
printf("\nP\tAT\tBT\tCT\tTAT\tWT\n");
for(i = 0; i < n; i++) {
printf("%d\t%d\t%d\t%d\t%d\t%d\n", p[i], at[i], bt[i], ct[i], tat[i], wt[i]);
}
printf("\nAvg Turnaround Time: %.2f", ttat / n);
printf("\nAvg Waiting Time: %.2f\n", twt / n);
}

OUTPUT
Enter how many processes:
4
Enter arrival time:
0000
Enter burst time:
3597

4
5
P AT BT CT TAT WT
1 0 3 3 3 0
2 0 5 8 8 3
3 0 9 17 17 8
4 0 7 24 24 17

Avg Turnaround Time: 13.00


Avg Waiting Time: 7.00

6
7
SJF
#include <stdio.h>
struct process
{
int ct, at, wt, tat, bt, completed;
};
void main()
{
int n;
printf("Enter the number of processes: ");
scanf("%d", &n);
struct process p[n];
for (int i = 0; i < n; i++)
{
printf("Enter the arrival time and burst time of process %d: ", i + 1);
scanf("%d%d", &p[i].at, &p[i].bt);
p[i].completed = 0;
}
int currenttime = 0, totalpc = 0, totaltat = 0, totalwt = 0;
while (totalpc < n)
{
int min = -1;
for (int i = 0; i < n; i++)
{
if (p[i].at <= currenttime && p[i].completed != 1)
{
if (min == -1 || p[i].bt < p[min].bt)
{
min = i;
}
}

8
ALGORITHM : SJF
1. Start
2. Read the number of processes n.
3. For each process, read arrival time at and burst time bt, and initialize completed to 0.
4. Initialize currenttime, totalpc, totaltat, and totalwt to 0.
5. While totalpc < n:
a. Set min to -1.
b. For each process:
 If the process has arrived and is not completed:
 Update min if this process has the shortest burst time.
c. If no process is found (min is -1), increment currenttime.
d. Otherwise:
 Update completion time, waiting time, and turnaround time for the selected process.
6. Print the results (process details and average times).
7. End

9
}
if (min == -1)
{
currenttime++;
}
else
{
p[min].ct = currenttime + p[min].bt;
currenttime += p[min].bt;
p[min].completed = 1;
totalpc++;
p[min].tat = p[min].ct - p[min].at;
p[min].wt = p[min].tat - p[min].bt;
totaltat += p[min].tat;
totalwt += p[min].wt;
}
}
printf("\nP\t\tAT\t\tBT\t\tCT\t\tTAT\t\tWT\n");
for (int i = 0; i < n; i++)
{
printf("%d\t\t%d\t\t%d\t\t%d\t\t%d\t\t%d\n", i + 1, p[i].at, p[i].bt, p[i].ct, p[i].tat, p[i].wt);
}
printf("Average TAT: %.2f\n", (float)totaltat / n);
printf("Average WT: %.2f\n", (float)totalwt / n);
}

OUTPUT
Enter the number of processes: 5
Enter the arrival time and burst time of process 1: 2 6
Enter the arrival time and burst time of process 2: 5 2
Enter the arrival time and burst time of process 3: 1 8
Enter the arrival time and burst time of process 4: 0 3

10
11
Enter the arrival time and burst time of process 5: 4 4

P AT BT CT TAT WT
1 2 6 9 7 1
2 5 2 11 6 4
3 1 8 23 22 14
4 0 3 3 3 0
5 4 4 15 11 7
Average TAT: 9.80
Average WT: 5.20

12
13
ROUND ROBIN
#include <stdio.h>
int main()
{
int n, i, j = 0, k = 0, q, totalwt = 0, totaltat = 0, totalpc = 0;
int ready_queue[100], minIndex = 0;
float avgtat, avgwt;
printf("Enter the number of processes: ");
scanf("%d", &n);
int bt[n], at[n], rt[n], wt[n], tat[n];
for (i = 0; i < n; i++)
{
printf("Enter the arrival time and burst time of process %d: ", i + 1);
scanf("%d %d", &at[i], &bt[i]);
rt[i] = bt[i];
}
printf("Enter the time quantum: ");
scanf("%d", &q);
int minat = at[0];
for (i = 1; i < n; i++)
{
if (at[i] < minat)
{
minat = at[i];
minIndex = i;
}
}
int ct = minat; ready_queue[k++]
= minIndex; while (totalpc < n)
{

14
ALGORITHM : ROUND ROBIN
1. Start.
2. Read the number of processes n.
3. For each process, read arrival time at and burst time bt, and initialize remaining time rt with bt.
4. Read the time quantum q.
5. Find the process with the minimum arrival time and initialize current time (ct) to that value.
6. Add the first process to the ready_queue.
7. While totalpc < n:
a. Get the current process from ready_queue.
b. If the remaining time rt[i] > 0 and the process has arrived:
 If rt[i] <= q, update ct, calculate turnaround time, and mark the process as complete.
 If rt[i] > q, decrement rt[i] and update ct.
c. Add any newly arrived processes to the ready_queue.
d. If the current process is not complete, add it back to the ready_queue.
8. Calculate total waiting time and turnaround time.
9. Print process details and average waiting/turnaround times.
10. End.

15
if (j == k)
{
break;
}
i = ready_queue[j++];
if (rt[i] > 0 && at[i] <= ct)
{
if (rt[i] <= q)
{
ct += rt[i];
tat[i] = ct - at[i];
rt[i] = 0;
wt[i] = tat[i] - bt[i];
totalpc++;
}
else
{
ct += q;
rt[i] -= q;
}
}
for (int l = 0; l < n; l++)
{
if (at[l] <= ct && rt[l] > 0)
{
int found = 0;
for (int m = 0; m < k; m++)
{
if (ready_queue[m] == l)
{
found = 1;

16
17
break;
}
}
if (!found)
{
ready_queue[k++] = l;
}
}
}
if (rt[i] > 0)
{
ready_queue[k++] = i;
}
}
for (i = 0; i < n; i++)
{
totalwt += wt[i];
totaltat += tat[i];
}
printf("\nProcess\tArrival Time\tBurst Time\tWaiting Time\tTurnaround Time\n");
for (i = 0; i < n; i++)
{
printf("%d\t\t%d\t\t%d\t\t%d\t\t%d\n", i + 1, at[i], bt[i], wt[i], tat[i]);
}
printf("\nAverage Waiting Time: %.2f\n", (float)totalwt / n);
printf("Average Turnaround Time: %.2f\n", (float)totaltat / n);
return 0;
}

OUTPUT
Enter the number of processes: 4
Enter the arrival time and burst time of process 1: 0 5

18
19
Enter the arrival time and burst time of process 2: 1 4
Enter the arrival time and burst time of process 3: 2 2
Enter the arrival time and burst time of process 4: 4 1
Enter the time quantum: 2

Process Arrival Time Burst Time Waiting Time Turnaround Time


1 0 5 7 12
2 1 4 6 10
3 2 2 2 4
4 4 1 4 5

Average Waiting Time: 4.75


Average Turnaround Time: 7.75

20
RESULT: The program has been executed successfully and the expected output has been obtained and
verified.

21
PROGRAM
SEQUENTIAL
#include <stdio.h>
void main()
{
int n,flag[50], len[20], start[20], t[20], bno[20][20];
int blockalloc[50]={0};
printf("Enter no.of files:");
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
printf("\nEnter the starting block of file.%d : ", i + 1);
scanf("%d", &start[i]);
printf("Enter length of file%d : ", i + 1);
scanf("%d", &len[i]);
flag[i]=1;
for(int j=start[i];j<start[i]+len[i];j++)
if(blockalloc[j]==1)
{
printf("Block.%d already allocated\n",j);
flag[i]=0;
break;
}
if(flag[i]){
for(int
j=start[i];j<start[i]+len[i];j++){ block
alloc[j]=1;
}
t[i] = start[i];
for (int j = 0; j < len[i]; j++)
bno[i][j] = t[i]++;
printf("File allocated successfully\n");

22
DATE:07/08/2024

EXPERIMENT NO.2
FILE ALLOCATION STRATEGIES

AIM: Simulate the following file allocation strategies


a) Sequential b) Indexed c) Linked
ALGORITHM: SEQUENTIAL
1. Start.
2. Initialize arrays for file properties and block allocation status.
3. Input the number of files.
4. For each file:
a. Input the starting block and length.
b. Check if the requested blocks are free:
 If any block is already allocated, indicate failure for that file.
 If all blocks are free, allocate them and mark them as used.
5. Display the allocation results for each file.
6. Implement a search loop:
a. Prompt for a file number.
b. If the file is allocated, display its details; otherwise, indicate it's not allocated.
c. Ask if the user wants to search for another file.
7. End.

23
}
}
printf("FileNo\tStart\tlength\n");
for (int i = 0; i < n; i++)
if(flag[i])
printf("%d\t\t %d \t\t%d\n", i + 1, start[i], len[i]);
int choice,search;
do{
printf("\nEnter file No:");
scanf("%d", &search);
if(flag[search-1]){
printf("File No : %d\n", search);
printf("Length : %d\n", len[search - 1]);
printf("blocks occupied:");
for (int i = 0; i < len[search - 1]; i++)
printf("%4d", bno[search - 1][i]);
}
else
printf("File%d not allocated \n",search);
printf("\nDo you want to search more (1/0) : ");scanf("%d",&choice);
}while(choice);
}

OUTPUT
Enter no.of files:2
Enter the starting block of file.1 : 3
Enter length of file1 : 2
File allocated successfully
Enter the starting block of file.2 : 6
Enter length of file2 : 2
File allocated successfully

24
25
FileNo Start length
1 3 2
2 6 2

Enter file No:2


File No : 2
Length : 2
blocks occupied: 6 7
Do you want to search more (1/0) : 1

Enter file No:1


File No : 1
Length : 2
blocks occupied: 3 4
Do you want to search more (1/0) : 0

26
27
INDEXED
#include <stdio.h>
void main() {
int n, allocated[10];
char fname[10][10];
int index[10];
int size[10];
int block[10][10];
for (int i = 0; i < 10; i++)
{ allocated[i] = 0;
}
printf("Enter no. of files: ");
scanf("%d", &n);
for (int i = 0; i < n; i++)
{ printf("\nEnter file name: ");
scanf("%s", fname[i]);
int validIndex = 0;
while (!validIndex) {
printf("Enter index block: ");
scanf("%d", &index[i]);
if (allocated[index[i]] == 0)
{ allocated[index[i]] = 1;
block[i][0] = index[i];
validIndex = 1;
} else {
printf("Index block is already allocated -- try another\n");
}
}
printf("Enter no.of blocks: ");
scanf("%d", &size[i]);

28
ALGORITHM: INDEXED
1. START
2. Initialize arrays: allocated, fname, index, size, and block.
3. Set all elements of allocated to 0.
4. Input number of files n.
5. For each file i from 0 to n-1:
a. Input file name fname[i].
b. Input index block index[i] and check allocation:
 If allocated, prompt for another block.
c. Input number of blocks size[i].
d. For each block j from 1 to size[i]:
 Input block number block[i][j] and check allocation:
 If allocated, prompt for another block.
e. Print index block and allocated blocks.
6. Print the table of files with their index and size.
7. END

29
for (int j = 1; j <= size[i]; j++)
{ int validBlock = 0;
while (!validBlock) {
printf("Enter block number %d: ", j);
scanf("%d", &block[i][j]);
if (allocated[block[i][j]] == 0) { allocated[block[i][j]]
= 1;
validBlock = 1;
} else {
printf("Block %d is already allocated --> enter another block\n", block[i][j]);
}
}
}
printf("\n");
for (int j = 1; j <= size[i]; j++) {
printf("%d-----> %d\n", block[i][0], block[i][j]);
}
}
printf("\nFile\tindex\tsize\n");
for (int i = 0; i < n; i++) {
printf("%s\t%d\t\t%d\n", fname[i], index[i], size[i]);
}
}

OUTPUT
Enter no. of files: 2
Enter file name: xyz
Enter index block: 3
Enter no.of blocks: 3
Enter block number 1: 4 2 1
Enter block number 2: Enter block number 3:
3---- > 4

30
31
3 ----> 2
3 ----> 1
Enter file name: abc
Enter index block: 4
Index block is already allocated -- try another
Enter index block: 5
Enter no.of blocks: 1
Enter block number 1: 1
Block 1 is already allocated --> enter another block
Enter block number 1: 6
5 ----> 6

File index size


xyz 3 3
abc 5 1

32
33
LINKED
#include <stdio.h>
void main() {
int n, allocated[10];
char fname[10][10];
int start[10];
int size[10];
int block[10][10];
for (int i = 0; i < 10; i++)
{ allocated[i] = 0;
}
printf("Enter no. of files: ");
scanf("%d", &n);
for (int i = 0; i < n; i++)
{ printf("\nEnter file name: ");
scanf("%s", fname[i]);
int validStart = 0;
while (!validStart) {
printf("Enter starting block: ");
scanf("%d", &start[i]);
if (allocated[start[i]] == 0)
{ allocated[start[i]] = 1;
block[i][0] = start[i];
validStart = 1;
} else {
printf("Starting block is already allocated --> enter another block\n");
}
}
printf("Enter no. of blocks: ");
scanf("%d", &size[i]);

34
ALGORITHM: LINKED
1. START
2. Initialize Variables:
a. allocated[10] to track allocated blocks (all initialized to 0).
b. fname[10][10] to store file names.
c. start[10] to store starting blocks for each file.
d. size[10] to store the number of blocks for each file.
e. block[10][10] to store allocated blocks for each file.
3. Input Number of Files:
a. Prompt the user for the number of files n.
4. For Each File (i = 0 to n-1):
a. Input File Name: Read fname[i].
b. Input Starting Block:
 Loop until a valid starting block is entered:
 Read start[i].
 Check if allocated[start[i]] is 0. If true, mark it as allocated and save it in block[i][0].
c. Input Number of Blocks: Read size[i].
d. Input Block Numbers:
 Loop for each block j (1 to size[i]):
 Loop until a valid block is entered:
 Read block[i][j].
 Check if allocated[block[i][j]] is 0. If true, mark it as allocated.
5. Output Allocation Information:
a. Print headers: "File, start, size, block".
b. For each file, print fname[i], start[i], size[i], and the block numbers.
6. END

35
printf("Enter block numbers:\n");
for (int j = 1; j <= size[i]; j++)
{ int validBlock = 0;
while (!validBlock)
{ scanf("%d",
&block[i][j]);
if (allocated[block[i][j]] == 0) { allocated[block[i][j]]
= 1;
validBlock = 1;
} else {
printf("Block %d is already allocated --> enter another block\n", block[i][j]);
}
}
}
}
printf("File\tstart\tsize\tblock\n");
for (int i = 0; i < n; i++) {
printf("%s\t%d\t\t%d\t", fname[i], start[i], size[i]);
for (int j = 1; j < size[i]; j++) {
printf("%d--->", block[i][j]);
}
printf("%d", block[i][size[i]]);
printf("\n");
}
}

OUTPUT
Enter no. of files: 2
Enter file name: xyz
Enter starting block: 2
Enter no. of blocks: 2
Enter block numbers:
35

36
37
Enter file name: abc
Enter starting block: 4
Enter no. of blocks: 2
Enter block numbers:
3
Block 3 is already allocated --> enter another block
6
8
File start size block
xyz 2 2 3--->5
abc 4 2 6--->8

38
RESULT: The program has been executed successfully and the expected output has been obtained and
verified.

39
PROGRAM
FCFS
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, total_movement = 0, previous, current, initial_head;
printf("Enter the number of disk requests: ");
scanf("%d", &n);
if (n <= 0) {
printf("Invalid number of disk requests.\n");
return 1;
}
int requests[n];
printf("Enter the disk request sequence:\n");
for (i = 0; i < n; i++) {
scanf("%d", &requests[i]);
}
printf("Enter the initial position of the disk head: ");
scanf("%d", &initial_head);
previous = initial_head;
printf("Sequence of disk access: %d", initial_head);
for (i = 0; i < n; i++) {
current = requests[i];
total_movement += abs(current - previous);
previous = current;
printf(" -> %d", current);
}
printf("\nTotal head movement: %d\n", total_movement);
printf("Average head movement: %.2f\n", (float)total_movement / n);
return 0;
}

40
DATE:14/08/2024

EXPERIMENT NO.3
DISK SCHEDULING ALGORITHMS

AIM: Simulate the following disk scheduling algorithms


a) FCFS b) SCAN C) C-SCAN
ALGORITHM: FCFS
1. START
2. Input Number of Disk Requests (n):
a. Read n. If n <= 0, print an error message and exit.
3. Input Disk Requests:
a. Create an array requests[n].
b. Read the disk request sequence into the array.
4. Input Initial Disk Head Position:
a. Read initial_head and set previous to initial_head.
5. Calculate Disk Movement:
a. Initialize total_movement to 0.
b. Print the initial head position.
c. For each request:
 Update current to the current request.
 Add the movement from previous to current to total_movement.

 Update previous to current.


 Print the current request.
6. Output Results:
a. Print the total head movement.
b. Print the average head movement.
7. END

41
OUTPUT
Enter the number of disk requests: 8
Enter the disk request sequence:
176 79 34 60 92 11 41 114
Enter the initial position of the disk head: 50
Sequence of disk access: 50 -> 176 -> 79 -> 34 -> 60 -> 92 -> 11 -> 41 -> 114
Total head movement: 510
Average head movement: 63.75

42
43
SCAN
#include <stdio.h>
#include <stdlib.h>
int main() {
int RQ[100], i, j, n, TotalHeadMovement = 0, initial, size, move, index = -1, temp;
printf("Enter the number of Requests\n");
scanf("%d", &n);
printf("Enter the Requests sequence\n");
for(i = 0; i < n; i++)
scanf("%d", &RQ[i]);
printf("Enter initial head position\n");
scanf("%d", &initial);
printf("Enter total disk size\n");
scanf("%d", &size);
printf("Enter the head movement direction for high (1) and for low (0)\n");
scanf("%d", &move);
for(i = 0; i < n; i++) {
for(j = 0; j < n - i - 1; j++) {
if(RQ[j] > RQ[j + 1]) {
temp = RQ[j]; RQ[j]
= RQ[j + 1];
RQ[j + 1] = temp;
}
}
}
for(i = 0; i < n; i++)
{ if(initial < RQ[i])
{
index = i;
break;
}
}

44
ALGORITHM: SCAN
1. Start
2. Declare n, head, max, diff, i, j, temp1, temp2, seek
3. Initialize seek = 0, temp1 = 0, temp2 = 0
4. Read the maximum disk size into max
5. Read the initial head position into head
6. Read the number of requests n
7. Declare queue[n+2], queue1[n+2], queue2[n+2]
8. Read each requested track from the user
a. For i from 1 to n
 Read temp
 If temp >= head
 Set queue1[temp1++] = temp
 Otherwise
 Set queue2[temp2++] = temp
9. Sort queue1 in ascending order using bubble sort
1. For j from 0 to temp1 - 1
o If queue1[j] > queue1[j+1], swap them
10. Sort queue2 in descending order using bubble sort
1. For j from 0 to temp2 - 1
o If queue2[j] < queue2[j+1], swap them
11. Set queue[0] = head
12. Add elements of queue1 to queue
a. Set i = 1
b. For j from 0 to temp1 - 1
 Set queue[i++] = queue1[j]
13. Set queue[i] = max
14. Add elements of queue2 to queue
a. Set i = temp1 + 2
b. For j from 0 to temp2 - 1
 Set queue[i++] = queue2[j]

45
printf("Initial head position: %d\n", initial);
printf("The Requests sequence is: ");
for(i = 0; i < n; i++) {
printf("%d ", RQ[i]);
}
printf("\n");
printf("Head movement sequence: %d ", initial);
if(move == 1) {
for(i = index; i < n; i++)
{ TotalHeadMovement += abs(RQ[i] -
initial); initial = RQ[i];
printf("%d ", initial);
}
if(index != n) {
TotalHeadMovement += abs(size - 1 - initial);
initial = size - 1;
printf("%d ", initial);
}
for(i = index - 1; i >= 0; i--)
{ TotalHeadMovement += abs(RQ[i] - initial);
initial = RQ[i];
printf("%d ", initial);
}
} else {
for(i = index - 1; i >= 0; i--)
{ TotalHeadMovement += abs(RQ[i] - initial);
initial = RQ[i];
printf("%d ", initial);
}
if(index != 0) {

46
15. Print each element of queue in order and calculate the seek time
a. For i from 0 to n + 1
 Set diff = abs(queue[i+1] - queue[i])
 Set seek += diff
 Display queue[i]
16. Display total seek time as seek
17. Display average seek time as seek / (float)n
18. Stop

47
TotalHeadMovement += abs(initial - 0);
initial = 0;
printf("%d ", initial);
}
for(i = index; i < n; i++)
{ TotalHeadMovement += abs(RQ[i] -
initial); initial = RQ[i];
printf("%d ", initial);
}
}
printf("\nTotal head movement is %d\n", TotalHeadMovement);
return 0;
}

OUTPUT
Enter the number of Requests
8
Enter the Requests sequence
176 79 34 60 92 11 41 114
Enter initial head position
50
Enter total disk size
200
Enter the head movement direction for high (1) and for low (0)
0
Initial head position: 50
The Requests sequence is: 11 34 41 60 79 92 114 176
Head movement sequence: 50 41 34 11 0 60 79 92 114 176
Total head movement is 226

48
49
C-SCAN
#include <stdio.h>
#include <stdlib.h>
int main() {
int RQ[100], i, j, n, TotalHeadMovement = 0, initial, size, move, index = 0, temp;
printf("Enter the number of Requests\n");
scanf("%d", &n);
printf("Enter the Requests sequence\n");
for (i = 0; i < n; i++)
scanf("%d", &RQ[i]);
printf("Enter initial head position\n");
scanf("%d", &initial);
printf("Enter total disk size\n");
scanf("%d", &size);
printf("Enter the head movement direction for high (1) and for low (0)\n");
scanf("%d", &move);
for (i = 0; i < n; i++) {
for (j = 0; j < n - i - 1; j++) {
if (RQ[j] > RQ[j + 1]) {
temp = RQ[j]; RQ[j]
= RQ[j + 1];
RQ[j + 1] = temp;
}
}
}
for (i = 0; i < n; i++)
{ if (initial < RQ[i])
{
index = i;
break;
}
}

50
ALGORITHM: C-SCAN
1. Start
2. Input number of requests n.
3. Input the request sequence RQ of size n.
4. Input the initial head position initial.
5. Input the total disk size.
6. Input the head movement direction move (1 for high, 0 for low).
7. Sort the request sequence RQ in ascending order.
8. Find the index where initial fits in the sorted request sequence.
9. Print the initial head position.
10. Print the sorted request sequence.
11. If move == 1 (move towards high end):
 Move from initial to the right (higher requests).
 Move to the end of the disk (size - 1).
 Move to the start of the disk (0).
 Move from the start to the remaining requests on the left (lower requests).
 Accumulate the total head movements.
12. Else (move == 0, move towards low end):
 Move from initial to the left (lower requests).
 Move to the start of the disk (0).
 Move to the end of the disk (size - 1).
 Move from the end to the remaining requests on the right (higher requests).
 Accumulate the total head movements.
13. Display the total head movement.
14. End

51
printf("Initial head position: %d\n", initial);
printf("The Requests sequence is: ");
for (i = 0; i < n; i++)
{ printf("%d ", RQ[i]);
}
printf("\n");
printf("Head movement sequence: %d ", initial);
if (move == 1) {
for (i = index; i < n; i++)
{ TotalHeadMovement += abs(RQ[i] -
initial); initial = RQ[i];
printf("%d ", initial);
}
TotalHeadMovement += abs(size - RQ[i - 1] - 1);
initial = size - 1;
printf("%d ", initial);
TotalHeadMovement += abs(size - 1 - 0);
initial = 0;
printf("%d ", initial);
for (i = 0; i < index; i++)
{ TotalHeadMovement += abs(RQ[i] -
initial); initial = RQ[i];
printf("%d ", initial);
}
} else {
for (i = index - 1; i >= 0; i--)
{ TotalHeadMovement += abs(RQ[i] - initial);
initial = RQ[i];
printf("%d ", initial);
}
TotalHeadMovement += abs(RQ[i + 1] - 0);

52
53
initial = 0;
printf("%d ", initial);
TotalHeadMovement += abs(size - 1 - 0);
initial = size - 1;
printf("%d ", initial);

for (i = n - 1; i >= index; i--)


{ TotalHeadMovement += abs(RQ[i] - initial);
initial = RQ[i];
printf("%d ", initial);
}
}
printf("\nTotal head movement is %d\n", TotalHeadMovement);
return 0;
}

OUTPUT
Enter the number of Requests
8
Enter the Requests sequence
176 79 34 60 92 11 41 114
Enter initial head position
50
Enter total disk size
200
Enter the head movement direction for high (1) and for low (0)
1
Initial head position: 50
The Requests sequence is: 11 34 41 60 79 92 114 176
Head movement sequence: 50 60 79 92 114 176 199 0 11 34 41
Total head movement is 389

54
RESULT: The program has been executed successfully and the expected output has been obtained and
verified.

55
PROGRAM
FIFO
#include <stdio.h>
int main() {
int numframes, numpages, i, j, k, pagefaults = 0;
int current = 0;
printf("Enter the number of frames: ");
scanf("%d", &numframes);
printf("Enter the number of pages: ");
scanf("%d", &numpages);
int frames[numframes], pages[numpages];
for (i = 0; i < numframes; i++) {
frames[i] = -1;
}
printf("Enter the page reference string: ");
for (i = 0; i < numpages; i++) {
scanf("%d", &pages[i]);
}
printf("\nPage Reference String: ");
for (i = 0; i < numpages; i++) {
printf("%d ", pages[i]);
}
printf("\n");
for (i = 0; i < numpages; i++)
{ int pagefound = 0;
for (j = 0; j < numframes; j++)
{ if (frames[j] == pages[i]) {
pagefound = 1;
break;
}
}

56
DATE:02/09/24

EXPERIMENT NO. 4
PAGE REPLACEMENT ALGORITHMS

AIM: Simulate the following page replacement algorithm


a) FIFO b) LRU c) LFU

ALGORITHM: FIFO
1. Start
2. Input the number of frames (numframes).
3. Input the number of pages (numpages).
4. Initialize the frame array (frames[]) to -1 for all positions.
5. Input the page reference string (pages[]) of size numpages.
6. Display the page reference string.
7. For each page in the page reference string:
a. Check if the page is already in the frame array (frames[]).

 If found, set pagefound = 1 (page hit).

 If not found (pagefound = 0), it's a page fault.


 Increment the page fault counter (pagefaults++).
 Replace the page in the current frame position (frames[current]).
 Update the current pointer to the next frame using circular logic (current = (current +
1) % numframes).
b. Print the current state of the frames.
8. Display the total number of page faults.
9. Display the total number of page hits (numpages - pagefaults).
10. End

57
if (!pagefound) {
printf("\nPage Fault: Page %d\n", pages[i]);
pagefaults++;
frames[current] = pages[i];
current = (current + 1) % numframes;
}
printf("Frames: ");
for (j = 0; j < numframes; j++)
{ printf("%d ", frames[j]);
}
printf("\n");
}
printf("\nTotal Page Faults: %d\n", pagefaults);
printf("\nTotal Page hit: %d\n", numpages - pagefaults);
return 0;
}

OUTPUT
Enter the number of frames: 3
Enter the number of pages: 12
Enter the page reference string: 1 2 3 4 1 2 5 1 2 3 4 5
Page Reference String: 1 2 3 4 1 2 5 1 2 3 4 5
Page Fault: Page 1
Frames: 1 -1 -1
Page Fault: Page 2
Frames: 1 2 -1
Page Fault: Page 3
Frames: 1 2 3
Page Fault: Page 4
Frames: 4 2 3
Page Fault: Page 1
Frames: 4 1 3

58
59
Page Fault: Page 2
Frames: 4 1 2
Page Fault: Page 5
Frames: 5 1 2
Frames: 5 1 2
Frames: 5 1 2
Page Fault: Page 3
Frames: 5 3 2
Page Fault: Page 4
Frames: 5 3 4
Frames: 5 3 4
Total Page Faults: 9
Total Page hit: 3

60
61
LRU
#include <stdio.h>
int main() {
int numframes, numpages, i, j, k, pagefaults = 0;
printf("Enter the number of frames: ");
scanf("%d", &numframes);
printf("Enter the number of pages: ");
scanf("%d", &numpages);
int frames[numframes], pages[numpages], recent[numframes];
for (i = 0; i < numframes; i++) {
frames[i] = -1;
recent[i] = 0;
}
printf("Enter the page reference string: ");
for (i = 0; i < numpages; i++) {
scanf("%d", &pages[i]);
}
printf("\nPage Reference String: ");
for (i = 0; i < numpages; i++) {
printf("%d ", pages[i]);
}
printf("\n");
for (i = 0; i < numpages; i++) {
int pagefound = 0, least_recent = 0;
for (j = 0; j < numframes; j++) {
if (frames[j] == pages[i])
{ pagefound = 1;
recent[j] = i;
break;
}
}

62
ALGORITHM: LRU
1. Start
2. Input the number of frames (numframes).
3. Input the number of pages (numpages).
4. Initialize:
a. frames[] array to -1 for all positions.
b. recent[] array to store the recent usage of pages.
c. pagefaults counter to 0.
5. Input the page reference string (pages[]) of size numpages.
6. Display the page reference string.
7. For each page in the page reference string:
a. Set pagefound = 0 and least_recent = 0.
b. Search if the page exists in the frame array (frames[]).
 If found (pagefound = 1), update recent[] with the current index to indicate the most recent
use.
 If not found (pagefound = 0), it's a page fault:
 Increment the pagefaults counter.
 Find the frame with the least recent use by checking recent[] values.
 Replace the least recently used page in the frame with the current page.
 Update recent[] with the current index.
c. Display the current frame status after each page access.
8. Display the total number of page faults.
9. Display the total number of page hits (numpages - pagefaults).
10. End

63
if (!pagefound) {
printf("\nPage Fault: Page %d\n", pages[i]);
pagefaults++;
for (j = 0; j < numframes; j++) {
if (recent[j] < recent[least_recent])
{ least_recent = j;
}
}
frames[least_recent] = pages[i];
recent[least_recent] = i;
}
printf("Frames: ");
for (j = 0; j < numframes; j++)
{ printf("%d ", frames[j]);
}
printf("\n");
}
printf("\nTotal Page Faults: %d\n", pagefaults);
printf("\nTotal Page hit: %d\n", numpages - pagefaults);
return 0;
}

OUTPUT
Enter the number of frames: 3
Enter the number of pages: 12
Enter the page reference string: 1 2 3 4 1 2 5 1 2 3 4 5
Page Reference String: 1 2 3 4 1 2 5 1 2 3 4 5
Page Fault: Page 1
Frames: 1 -1 -1
Page Fault: Page 2
Frames: 2 -1 -1
Page Fault: Page 3
Frames: 2 3 -1

64
65
Page Fault: Page 4
Frames: 2 3 4
Page Fault: Page 1
Frames: 1 3 4
Page Fault: Page 2
Frames: 1 2 4
Page Fault: Page 5
Frames: 1 2 5
Frames: 1 2 5
Frames: 1 2 5
Page Fault: Page 3
Frames: 1 2 3
Page Fault: Page 4
Frames: 4 2 3
Page Fault: Page 5
Frames: 4 5 3
Total Page Faults: 10
Total Page hit: 2

66
67
LFU
#include <stdio.h>
void main()
{
int i, j, num_pages, num_frames, page_fault = 0;
printf("Enter number of frames: ");
scanf("%d", &num_frames);
printf("Enter number of pages: ");
scanf("%d", &num_pages);
int pages[num_pages], frames[num_frames], freq[num_frames], time[num_frames];
printf("Enter page reference string: ");
for (i = 0; i < num_pages; i++)
scanf("%d", &pages[i]);
for (i = 0; i < num_frames; i++)
{
frames[i] = -1;
freq[i] = 0;
time[i] = 0;
}

printf("\nLFU Page replacement algorithm\n\n");


for (i = 0; i < num_pages; i++)
{
int found = 0;
for (j = 0; j < num_frames; j++)
{
if (pages[i] == frames[j])
{
found = 1;
printf("Page Hit: Page: %d\n", pages[i]);
freq[j]++;

68
ALGORITHM: LFU
1. Start
2. Input the number of frames (num_frames).
3. Input the number of pages (num_pages).
4. Initialize arrays:
a. frames[] to store the pages currently in the frames, initially set to -1.
b. freq[] to store the frequency of how many times each frame is used, initially set to 0.
c. time[] to store the time when a page was loaded into a frame, initially set to 0.
5. Input the page reference string (pages[]), containing the sequence of pages requested.
6. For each page in the page reference string:
a. Set found = 0 (flag to check if the page is in the frame).
b. Check if the current page is already in any of the frames:
 If found, mark it as a page hit, increment its frequency in the freq[] array, and set
found = 1.
c. If not found (page fault occurs):
 Find the least frequently used (LFU) page:
 Loop through all frames and find the frame with the smallest frequency or, in
case of ties, the least recently used page (using the time[] array).
 If an empty frame (frame value = -1) is found, use it to place the new page.
 Replace the least frequently used page in the frame with the current page.
 Update the freq[] and time[] arrays for the selected frame.
7. Display the current status of the frames after each page access.
8. Track the total number of page faults (page_fault).
9. Calculate the total number of page hits as num_pages - page_fault.
10. Display the total number of page faults and page hits.
11. End

69
break;
}
}
if (!found)
{
int lfu = 0;
for (j = 0; j < num_frames; j++)
{
if (frames[j] == -1)
{
lfu = j;
break;
}
if (freq[j] < freq[lfu] || (freq[lfu] == freq[j] && time[j] < time[lfu]))
lfu = j;
}
printf("Page Fault: Page: %d\n", pages[i]);
page_fault++;
frames[lfu] = pages[i];
freq[lfu] = 1;
time[lfu] = i;
}
printf("Frames: \n");
for (j = 0; j < num_frames; j++)
printf("%d ", frames[j]);
printf("\n");
}
printf("Total page faults: %d\n", page_fault);
printf("Total page hits: %d", num_pages - page_fault);
}

70
71
OUTPUT
Enter number of frames: 3
Enter number of pages: 11
Enter page reference string: 1 2 0 3 0 4 0 2 3 0 3
LFU Page replacement algorithm
Page Fault: Page: 1
Frames:
1 -1 -1
Page Fault: Page: 2
Frames:
1 2 -1
Page Fault: Page: 0
Frames:
120
Page Fault: Page: 3
Frames:
320
Page Hit: Page: 0
Frames:
320
Page Fault: Page: 4
Frames:
340
Page Hit: Page: 0
Frames:
340
Page Fault: Page: 2
Frames:
240
Page Fault: Page: 3
Frames:

72
73
230
Page Hit: Page: 0
Frames:
230
Page Hit: Page: 3
Frames:
230
Total page faults: 7
Total page hits: 4

74
RESULT: The program has been executed successfully and the expected output has been obtained and
verified.

75
PROGRAM
PASS 1
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void passOne(char label[10], char opcode[10], char operand[10], char code[10], char mnemonic[3]);
void display();
int main()
{
char label[10], opcode[10], operand[10];
char code[10], mnemonic[3];
passOne(label, opcode, operand, code, mnemonic);
return 0;
}
void passOne(char label[10], char opcode[10], char operand[10], char code[10], char mnemonic[3])
{
int locctr, start, length;
FILE *fp1, *fp2, *fp3, *fp4, *fp5;
fp1 = fopen("input.txt", "r");
fp2 = fopen("optab.txt", "r");
fp3 = fopen("symtab.txt", "w");
fp4 = fopen("intermediate.txt", "w");
fp5 = fopen("length.txt", "w");
fscanf(fp1, "%s\t%s\t%s", label, opcode, operand);
if (strcmp(opcode, "START") == 0) {
start = atoi(operand);
locctr = start;
fprintf(fp4, "\t%s\t%s\t%s\n", label, opcode, operand);
fscanf(fp1, "%s\t%s\t%s", label, opcode, operand);
}
else {

76
DATE: 11/09/2024

EXPERIMENT NO. 5
PASS 1 OF II PASS ASSEMBLER

AIM: Implement Pass 1 of II Pass Assembler.


ALGORITHM:
1. Open the required files:
2. Read the first line of `input.txt`:
- If the opcode is `"START"`:
- Save the operand as starting address and store it in the `locctr`.
- Write this line to `intermediate.txt`.
- Read the next line of `input.txt`.
- Else
- Set `locctr = 0`.
3. Main Loop(Repeat until the `opcode` is `"END"`):
- Write to Intermediate File (`intermediate.txt`):
- Write the current value of `locctr` along with the current line’s label, opcode, and operand to
`intermediate.txt`.
- Add Labels to Symbol Table (`symtab.txt`):
- If the label is not `"**"` (i.e., it is a valid label), write the label and its corresponding `locctr` to
`symtab.txt`.
- Search for the Opcode in `optab.txt`:
- If found, increment the `locctr` by 3
- else
- If the opcode is:
- "WORD": Add 3 to the `locctr`.
- "RESW": Add `3 * operand` to `locctr`.
- "BYTE": Add constant(length of byte) to the `locctr`.
- "RESB": Add the operand (number of bytes to reserve) directly to the `locctr`.
- Read the next line from `input.txt`.
4. Once the opcode is `"END"`, write the final line (with the `locctr`) to `intermediate.txt`.

77
locctr = 0;
}
while (strcmp(opcode, "END") != 0) {
fprintf(fp4, "%d\t%s\t%s\t%s\n", locctr, label, opcode, operand);
if (strcmp(label, "**") != 0) {
fprintf(fp3, "%s\t%d\n", label, locctr);
}
fscanf(fp2, "%s\t%s", code, mnemonic);
while (strcmp(code, "END") != 0) {
if (strcmp(opcode, code) == 0)
{ locctr += 3;
break;
}
fscanf(fp2, "%s\t%s", code, mnemonic);
}
if (strcmp(opcode, "WORD") == 0)
{ locctr += 3;
}
else if (strcmp(opcode, "RESW") == 0)
{ locctr += (3 * (atoi(operand)));
}
else if (strcmp(opcode, "BYTE") == 0)
{ if (operand[0] == 'C') {
locctr += (strlen(operand) - 3);
}
else if (operand[0] == 'X') {
locctr += (strlen(operand) - 3) / 2;
}
}
else if (strcmp(opcode, "RESB") == 0)
{ locctr += atoi(operand);

78
5. Calculate Program Length:
- `length = locctr - start` (where `start` is the address from the `START` directive).
- Write the length of the program to `length.txt`.
6. Close All Files.
7. Display the Contents of Files .
8. End of Pass 1.

79
}
fscanf(fp1, "%s\t%s\t%s", label, opcode, operand);
}
fprintf(fp4, "%d\t%s\t%s\t%s\n", locctr, label, opcode, operand);
fclose(fp4);
fclose(fp3);
fclose(fp2);
fclose(fp1);
display();
length = locctr - start;
fprintf(fp5, "%d", length);
fclose(fp5);
printf("\nThe length of the code : %d\n", length);
}
void display()
{ char str;
FILE *fp1, *fp2, *fp3;
fp1 = fopen("input.txt", "r");
str = fgetc(fp1);
/* while (str != EOF)
{
printf("%c", str);
str = fgetc(fp1);
} */
fclose(fp1);
printf("\n\n intermediate.txt :\n\n");
fp2 = fopen("intermediate.txt", "r");
str = fgetc(fp2);
while (str != EOF) {
printf("%c", str);
str = fgetc(fp2);

80
81
}
fclose(fp2);
printf("\n\nThe contents of Symbol Table :\n\n");
fp3 = fopen("symtab.txt", "r");
str = fgetc(fp3);
while (str != EOF) {
printf("%c", str);
str = fgetc(fp3);
}
fclose(fp3);
}

input.txt
** START 2000
** LDA FIVE
** STA ALPHA
** LDCH CHARZ
** STCH C1
ALPHA RESW 2
FIVE WORD 5
CHARZ BYTE C'Z'
C1 RESB 1
** END **

optab.txt
LDA 03
STA 0f
LDCH 53
STCH 57
END *

82
83
OUTPUT

intermediate.txt
** START 2000
2000 ** LDA FIVE
2003 ** STA ALPHA
2006 ** LDCH CHARZ
2009 ** STCH C1
2012 ALPHA RESW 2
2018 FIVE WORD 5
2021 CHARZ BYTE C'Z'
2022 C1 RESB 1
2023 ** END **

symtab.txt
ALPHA 2012
FIVE 2018
CHARZ 2021
C1 2022
The length of the code : 23

84
RESULT: The program has been executed successfully and the expected output has been obtained and
verified.

85
PROGRAM
PASS 2
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void display();
void swap(char *x, char *y)
{ char t = *x; *x = *y; *y =
t;
}
char* reverse(char *buffer, int i, int j)
{
while (i < j) {
swap(&buffer[i++], &buffer[j--]);
}
return buffer;
}
char* itoa(int value, char* buffer, int base)
{
if (base < 2 || base > 32)
{ return buffer;
}
int n = abs(value);
int i = 0;
while (n)
{
int r = n % base;
if (r >= 10) {
buffer[i++] = 65 + (r - 10);
}
else {
buffer[i++] = 48 + r;

86
DATE:25/09/2024

EXPERIMENT NO. 5
PASS 2 OF II PASS ASSEMBLER

AIM: Implement Pass 2 of II Pass Assembler.


ALGORITHM:
1. Declare required variables.
2. Initialize
- `mnemonic[15][15] = {"LDA", "STA", "LDCH", "STCH"}` (example set).
- `code[15][15] = {"03", "0f", "53", "57"}` (corresponding machine codes).
3. Open files for reading and writing:
4. If any file fails to open, print an error message and exit the program.
5. Read through `intermediate.txt` to find the final address.
6. Reopen `intermediate.txt` from the beginning.
7. If the first opcode is `START`, write the starting details to:
- `output.txt` for final output.
- `objcode.txt` for generating the header record `H`.
8. Generate Object Code
i. Loop through `intermediate.txt` until `END` opcode:
ii. For each opcode:
- If `opcode == "BYTE"`:
- Convert the characters in the operand to hexadecimal and write the values to both `output.txt`
and `objcode.txt`.
- If `opcode == "WORD"`:
- Convert the operand (integer) to decimal.
- Write the operand as a 6-digit value to both `output.txt` and `objcode.txt`.
- If `opcode == "RESB"` or `opcode == "RESW"`:
- Write their details only to `output.txt` .
- If the operand refers to a symbol
- Search for the symbol in the SYMTAB and retrieve its address.
- Combine the opcode's machine code with the operand's address to form the final object code.

87
}
n = n / base;
}
if (i == 0)
{ buffer[i++] = '0';
}
if (value < 0 && base == 10)
{ buffer[i++] = '-';
}
buffer[i] = '\0';

return reverse(buffer, 0, i - 1);


}
int main()
{
char a[10], ad[10], label[10], opcode[10], operand[10], symbol[10];
int start, diff, i, address, add, len, actual_len, finaddr, prevaddr, j = 0,l;
char mnemonic[15][15] = {"LDA", "STA", "LDCH", "STCH"};
char code[15][15] = {"03", "0f", "53", "57"};
FILE *fp1, *fp2, *fp3, *fp4,*fp5;
fp1 = fopen("output.txt", "w");
fp2 = fopen("symtab.txt", "r");
fp3 = fopen("intermediate.txt", "r");
fp4 = fopen("objcode.txt", "w");
fp5 = fopen("length.txt", "r");
fscanf(fp3, "%s\t%s\t%s", label, opcode, operand);
while (strcmp(opcode, "END") != 0)
{
prevaddr = address;
fscanf(fp3, "%d%s%s%s", &address, label, opcode, operand);
}

88
- Write this object code to both `output.txt` and `objcode.txt`.
9. Write the end record (`E`) to `objcode.txt`.
10. Close all open files.
11. Display the contents of each file.
12. Exit the Program.

89
finaddr = address;
fclose(fp3);
fp3 = fopen("intermediate.txt", "r");
fscanf(fp3, "\t%s\t%s\t%s", label, opcode, operand);
if (strcmp(opcode, "START") == 0)
{
fprintf(fp1, "\t%s\t%s\t%s\n", label, opcode, operand);
fscanf(fp5,"%d",&l);
fprintf(fp4, "H^%s^00%s^0000%d\n", label, operand, l);
fscanf(fp3, "%d%s%s%s", &address, label, opcode, operand);
start = address;
diff = prevaddr - start;
fprintf(fp4, "T^00%d^%d", address, diff);
}
while (strcmp(opcode, "END") != 0)
{
if (strcmp(opcode, "BYTE") == 0)
{
fprintf(fp1, "%d\t%s\t%s\t%s\t", address, label, opcode, operand);
len = strlen(operand);
actual_len = len - 3;
fprintf(fp4, "^");
for (i = 2; i < (actual_len + 2); i++)
{
itoa(operand[i], ad, 16);
fprintf(fp1, "%s", ad);
fprintf(fp4, "%s", ad);
}
fprintf(fp1, "\n");
}
else if (strcmp(opcode, "WORD") == 0)

90
91
{
len = strlen(operand);
itoa(atoi(operand), a, 10);
fprintf(fp1, "%d\t%s\t%s\t%s\t00000%s\n", address, label, opcode, operand, a);
fprintf(fp4, "^00000%s", a);
}
else if ((strcmp(opcode, "RESB") == 0) || (strcmp(opcode, "RESW") == 0))
{ fprintf(fp1, "%d\t%s\t%s\t%s\n", address, label, opcode, operand);
}
else
{
while (strcmp(opcode, mnemonic[j]) != 0)
j++;
if (strcmp(operand, "COPY") == 0)
fprintf(fp1, "%d\t%s\t%s\t%s\t%s0000\n", address, label, opcode, operand, code[j]);
else
{
rewind(fp2);
fscanf(fp2, "%s%d", symbol, &add);
while (strcmp(operand, symbol) != 0)
fscanf(fp2, "%s%d", symbol, &add);
fprintf(fp1, "%d\t%s\t%s\t%s\t%s%d\n", address, label, opcode, operand, code[j], add);
fprintf(fp4, "^%s%d", code[j], add);
}
}
fscanf(fp3, "%d%s%s%s", &address, label, opcode, operand);
}
fprintf(fp1, "%d\t%s\t%s\t%s\n", address, label, opcode, operand);
fprintf(fp4, "\nE^00%d", start);
fclose(fp5);
fclose(fp4);

92
93
fclose(fp3);
fclose(fp2);
fclose(fp1);
display();
return 0;
}

void display()

{ char ch;
FILE *fp1, *fp2, *fp3, *fp4;

printf("\n\n intermediate.txt \n\n");


fp3 = fopen("intermediate.txt", "r");
ch = fgetc(fp3);
while (ch != EOF)

printf("%c", ch);
ch = fgetc(fp3);
}

fclose(fp3);

printf("\n\n symtab.txt :\n\n");

fp2 = fopen("symtab.txt", "r");


ch = fgetc(fp2);
while (ch != EOF)
{

printf("%c", ch);
ch = fgetc(fp2);
}

fclose(fp2);

printf("\n\n output.txt:\n\n"); fp1 =


fopen("output.txt", "r");
ch = fgetc(fp1);

94
95
while (ch != EOF)
{
printf("%c", ch);
ch = fgetc(fp1);
}
fclose(fp1);
printf("\n\n Object Program:\n\n"); fp4 =
fopen("objcode.txt", "r");
ch = fgetc(fp4);
while (ch != EOF)
{
printf("%c", ch);
ch = fgetc(fp4);
}
fclose(fp4);
}

OUTPUT

intermediate.txt

** START 2000
2000 ** LDA FIVE
2003 ** STA ALPHA
2006 ** LDCH CHARZ
2009 ** STCH C1
2012 ALPHA RESW 2
2018 FIVE WORD 5
2021 CHARZ BYTE C'Z'
2022 C1 RESB 1
2023 ** END **

96
97
symtab.txt
ALPHA 2012
FIVE 2018
CHARZ 2021
C1 2022

output.txt
** START 2000
2000 ** LDA FIVE 032018
2003 ** STA ALPHA 0f2012
2006 ** LDCH CHARZ 532021
2009 ** STCH C1 572022
2012 ALPHA RESW 2
2018 FIVE WORD 5 000005
2021 CHARZ BYTE C'Z' 5A
2022 C1 RESB 1
2023 ** END **

Object Program:
H^**^002000^000023
T^002000^22^032018^0f2012^532021^572022^000005^5A
E^002000

98
RESULT:The program has been executed successfully and the expected output has been obtained and
verified.

99
PROGRAM
SINGLE PASS
#include <stdio.h>

#include <string.h>

#include <stdlib.h>

void swap(char *x, char *y)

{ char t = *x; *x = *y; *y = t;

char* reverse(char *buffer, int i, int j)

while (i < j) {

swap(&buffer[i++], &buffer[j--]);

return buffer;

char* itoa(int value, char* buffer, int base)

{ if (base < 2 || base > 32)

{ return buffer;

int n = abs(value);

int i = 0;

while (n) {

int r = n % base;

if (r >= 10) {

100
DATE:07/10/2024

EXPERIMENT NO. 6

SINGLE PASS ASSEMBLER

AIM: Implement Single Pass Assembler.

ALGORITHM:

1. Begin

2. Read first input line

3. if OPCODE="START" then

a. save #[operand) as starting address

b. initialize LOCCTR as starting address

c. read next input line end

4. else initialize LOCCTR to 0

5. while OPCODE != "END" do

- if there is not a comment line then

- if there is a symbol in the LABEL field then

i. search SYMTAB for LABEL

ii. if found then

1. if symbol value as null

2. set symbol value as LOCCTR and search the linked list with the

corresponding operand.

3.PTR addresses and generate operand addresses as corresponding symbol values.

4. set symbol value as LOCCTR in symbol table and delete the

linked list

iii. end

iv. else insert (LABEL, LOCCTR) into SYMTAB

v. End
6. search OPTAB for OPCODE

7. If found then search SYMTAB for OPERAND address

101
buffer[i++] = 65 + (r - 10);
}

else {

buffer[i++] = 48 + r;

n = n / base;

if (i == 0)

{ buffer[i++] = '0';

if (value < 0 && base == 10)

{ buffer[i++] = '-';

buffer[i] = '\0';

return reverse(buffer, 0, i - 1);

void main(){

char opcode[10], operand[10], label[10], a[10], ad[10], symbol[10], ch;

char code[10][10], code1[10][10] = {"03", "0f", "53", "57"};

char mnemonic[10][10] = {"START", "LDA", "STA", "LDCH", "STCH", "END"};

char mnemonic1[10][10] = {"LDA", "STA", "LDCH", "STCH"};

int locctr, start, length, i = 0, j = 0, k, l = 0;

int st, diff, address, add, len, actual_len, finaddr, prevaddr;

FILE *fp1, *fp2, *fp3, *fp4, *fp5, *fp6, *fp7;

fp1 = fopen("input.txt", "r");

102
8. if found then

- if symbol value not equal to null then

- store symbol value as operand address

- else insert at the end of the linked list with a node with address as

LOCCTR

9. else insert (symbol name, null) add 3 to LOCCTR.

10. else if OPCODE="WORD" then add 3 to LOCCTR & convert comment to

object code

11. else if OPCODE=RESW" then add 3 #[OPERND] to LOCCTR

12. else if OPCODE=RESB" then add #[OPERNO] to LOCCTR

13. else if OPCODE BYTE" then find length of the constant in bytes. add

length to LOCCTR convert constant to object code.

14 if object code will not fit into current text record then write text record to

object program.

- initialize new text record.

- add object code to text record.

15 write listing line

16. read next input line

17. write last text record to object program

18 write end record to object program

19. write last listing line


20. End

103
fp2 = fopen("symtab.txt", "w");

fp3 = fopen("intermediate.txt", "w");

fscanf(fp1, "%s%s%s", label, opcode, operand);

if (strcmp(opcode, "START") == 0)

start = atoi(operand);

locctr = start;

fprintf(fp3, "%s\t%s\t%s\n", label, opcode, operand);

fscanf(fp1, "%s%s%s", label, opcode, operand);

else

locctr = 0;

while (strcmp(opcode, "END") != 0)

fprintf(fp3, "%d", locctr);

if (strcmp(label, "**") != 0)

fprintf(fp2, "%s\t%d\n", label, locctr);

strcpy(code[i], mnemonic[j]);

while (strcmp(mnemonic[j], "END") != 0)

if (strcmp(opcode, mnemonic[j]) == 0)

locctr += 3;

break;

104
105
}

strcpy(code[i], mnemonic[j]);

j++;

if (strcmp(opcode, "WORD") == 0)

locctr += 3;

else if (strcmp(opcode, "RESW") == 0)

locctr += (3 * (atoi(operand)));

else if (strcmp(opcode, "RESB") == 0)

locctr += (atoi(operand));

else if (strcmp(opcode, "BYTE") == 0)

++locctr;

fprintf(fp3, "\t%s\t%s\t%s\n", label, opcode, operand);

fscanf(fp1, "%s%s%s", label, opcode, operand);

fprintf(fp3, "%d\t%s\t%s\t%s\n", locctr, label, opcode, operand);

length = locctr - start;

fclose(fp3);

fclose(fp2);

fclose(fp1);

fp1 = fopen("input.txt", "r");

ch = fgetc(fp1);

/*

while (ch != EOF)

{ printf("%c", ch);

106
107
ch = fgetc(fp1);

} */

printf("\n\nLength of the input program is %d.", length);

printf("\n\n symtab.txt\n\n");

fp2 = fopen("symtab.txt", "r");

ch = fgetc(fp2);

while (ch != EOF)

printf("%c", ch);

ch = fgetc(fp2);

fclose(fp2);

fclose(fp1);

fp4 = fopen("output.txt", "w");

fp5 = fopen("symtab.txt", "r");

fp6 = fopen("intermediate.txt", "r");

fp7 = fopen("objcode.txt", "w");

fscanf(fp6, "%s%s%s", label, opcode, operand);

while (strcmp(opcode, "END") != 0)

{ prevaddr = address;

fscanf(fp6, "%d%s%s%s", &address, label, opcode, operand);

finaddr = address;

fclose(fp6);

fp6 = fopen("intermediate.txt", "r");

108
109
fscanf(fp6, "%s%s%s", label, opcode, operand);

if (strcmp(opcode, "START") == 0)

{ fprintf(fp4, "\t%s\t%s\t%s\n", label, opcode, operand);

fprintf(fp7, "H^%s^00%s^0000%d\n", label, operand, length);

fscanf(fp6, "%d%s%s%s", &address, label, opcode, operand);

st = address;

diff = prevaddr - st;

fprintf(fp7, "T^00%d^%d", address, diff);

while (strcmp(opcode, "END") != 0)

if (strcmp(opcode, "BYTE") == 0)

fprintf(fp4, "%d\t%s\t%s\t%s\t", address, label, opcode, operand);

len = strlen(operand);

actual_len = len - 3;

fprintf(fp7, "^");

for (k = 2; k < (actual_len + 2); k++)

{ itoa(operand[k], ad, 16);

fprintf(fp4, "%s", ad);

fprintf(fp7, "%s", ad);

fprintf(fp4, "\n");

else if (strcmp(opcode, "WORD") == 0)

110
111
{ len = strlen(operand);

itoa(atoi(operand), a, 10);

fprintf(fp4, "%d\t%s\t%s\t%s\t00000%s\n", address, label, opcode, operand, a);

fprintf(fp7, "^00000%s", a);

else if ((strcmp(opcode, "RESB") == 0) || (strcmp(opcode, "RESW") == 0))

fprintf(fp4, "%d\t%s\t%s\t%s\n", address, label, opcode, operand);

else

{ while (strcmp(opcode, mnemonic1[l]) != 0)

l++;

if (strcmp(operand, "COPY") == 0)

fprintf(fp4, "%d\t%s\t%s\t%s\t%s0000\n", address, label, opcode,

operand, code1[l]);

else

{ rewind(fp5);

fscanf(fp5, "%s%d", symbol, &add);

while (strcmp(operand, symbol) != 0)

fscanf(fp5, "%s%d", symbol, &add);

fprintf(fp4, "%d\t%s\t%s\t%s\t%s%d\n", address, label, opcode, operand, code1[l], add);

fprintf(fp7, "^%s%d", code1[l], add);

}
}
fscanf(fp6, "%d%s%s%s", &address, label, opcode, operand);

}
fprintf(fp4, "%d\t%s\t%s\t%s\n", address, label, opcode, operand);

112
113
fprintf(fp7, "\nE^00%d", st);
printf("\n\n output.txt \n\n");

fp1 = fopen("output.txt", "r");


ch = fgetc(fp1);

while (ch != EOF)

{ printf("%c", ch);

ch = fgetc(fp1);
}
printf("\nObject Program has been generated.");

fclose(fp7);

fclose(fp6);

fclose(fp5);

fclose(fp4);

printf("\n\n Object Program:\n\n");

fp7 = fopen("objcode.txt", "r");

ch = fgetc(fp7);

while (ch != EOF)

{ printf("%c", ch);

ch = fgetc(fp7);

} fclose(fp7);

}
input.txt
** START 2000
** LDA FIVE
** STA ALPHA
** LDCH CHARZ
** STCH C1
ALPHA RESW 2
FIVE WORD 5
CHARZ BYTE C'Z'

114
115
C1 RESB 1

** END **

optab.txt
LDA 03
STA 0f
LDCH 53
STCH 57
END *

OUTPUT

output.txt
** START 2000
2000 ** LDA FIVE 032018
2003 ** STA ALPHA 0f2012
2006 ** LDCH CHARZ 532021
2009 ** STCH C1 572022
2012 ALPHA RESW 2
2018 FIVE WORD 5 000005
2021 CHARZ BYTE C'Z' 5A
2022 C1 RESB 1
2023 ** END **

Length of the input program is 23

symtab.txt

ALPHA 2012

FIVE 2018

CHARZ 2021

C1 2022

Object Program has been generated.

116
117
.Object Program:

H^**^002000^000023
T^002000^22^032018^0f2012^532021^572022^000005^5a
E^002000

118
RESULT:The program has been executed successfully and the expected output has been obtained and
verified.

119
PROGRAM
ABSOLUTE LOADER
#include <stdio.h>
#include <string.h>
char input[10], label[10], ch1, ch2;
int addr, w = 0, start, ptaddr, l, length = 0, end, count = 0, k,
taddr, address, i = 0;
FILE *fp1, *fp2;
void check();
void main()
{
fp1 = fopen("input.txt", "r");
fp2 = fopen("output.txt", "w");
fscanf(fp1, "%s", input);
printf("\n\nABSOLUTE LOADER\n");
fprintf(fp2, "\n \n");
fprintf(fp2, "MEMORY ADDRESS\t\t\tCONTENTS");
fprintf(fp2, "\n \n");
while (strcmp(input, "E") != 0)
{
if (strcmp(input, "H") == 0)
{
fscanf(fp1, "%s %x %x %s", label, &start, &end, input);
address = start;
}
else if (strcmp(input, "T") == 0)
{
l = length;
ptaddr = addr;
fscanf(fp1, "%x %x %s", &taddr, &length, input);
addr = taddr;
if (w == 0)
{
ptaddr = address;
120
DATE:14/10/2024

EXPERIMENT NO. 8
ABSOLUTE LOADER

AIM: Implement an Absolute Loader


ALGORITHM:
1. Start
2. Read the Header record.
3. Verify the program name and length.
4. Read the first Text record.
5. While the record type is not 'E' (End record), do:
a) If the object code is in character form, convert it into internal representation.
b) Move the object code to the specified location in memory.
c) Read the next object program record.
6. Jump to the address specified in the End record.
7. End

121
w = 1;
}
for (k = 0; k < (taddr - (ptaddr + l)); k++)
{
address = address + 1;
fprintf(fp2, "xx");
count++;
if (count == 4)
{
fprintf(fp2, " ");
i++;
if (i == 4)
{
fprintf(fp2, "\n\n%x\t\t", address);
i = 0;
}
count = 0;
}
}
if (taddr == start)
fprintf(fp2, "\n\n%x\t\t", taddr);
fprintf(fp2, "%c%c", input[0], input[1]);
check();
fprintf(fp2, "%c%c", input[2], input[3]);
check();
fprintf(fp2, "%c%c", input[4], input[5]);
check();
fscanf(fp1, "%s", input);
}
else
{
fprintf(fp2, "%c%c", input[0], input[1]);
check();
fprintf(fp2, "%c%c", input[2], input[3]);

122
123
check();
fprintf(fp2, "%c%c", input[4], input[5]);
check();
fscanf(fp1, "%s", input);
}
}
fprintf(fp2, "\n \n");
fclose(fp1);
fclose(fp2);
fp2 = fopen("output.txt", "r");
ch2 = fgetc(fp2);
while (ch2 != EOF)
{
printf("%c", ch2);
ch2 = fgetc(fp2);
}
fclose(fp2);
}
void check()
{
count++;
address++;
taddr = taddr + 1;
if (count == 4)
{
fprintf(fp2, " ");
i++;
if (i == 4)
{
fprintf(fp2, "\n\n%x\t\t", taddr);
i = 0;
}
count = 0; } }

124
125
Input.txt
H COPY 001000 00107A
T 001000 1E 141033 482039 001036 281030 301015 482061 3C1003 00102A 0C1039 00102D
T 00101E 15 0C1036 482061 081033 4C0000 454F46 000003 000000
T 001047 1E 041030 001030 E0205D 30203F D8205D 281030 302057 549039 2C205E 38203F
T 001077 1C 101036 4C0000 000000 001000 041030 E02079 302064 509039 DC2079 2C1036
E 001000

OUTPUT
ABSOLUTE LOADER

MEMORY ADDRESS CONTENTS

1000 14103348 20390010 36281030 30101548

1010 20613C10 0300102A 0C103900 102D0C10

1020 36482061 0810334C 0000454F 46000003

1030 000000xx xxxxxxxx xxxxxxxx xxxxxxxx

1040 xxxxxxxx xxxxxx04 10300010 30E0205D

1050 30203FD8 205D2810 30302057 5490392C

1060 205E3820 3Fxxxxxx xxxxxxxx xxxxxxxx

1070 xxxxxxxx xxxxxx10 10364C00 00000000

1080 00100004 1030E020 79302064 509039DC

1090 20792C10 36

126
RESULT: The program has been executed successfully and the expected output has been obtained andverified.

127
PROGRAM
RELOCATION LOADER
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
char add[6],length[10],input[10],binary[12],bitmask[12],relocbit,ch2;
int start,inp,len,i,address,opcode,addr,actualadd;
FILE *fp1,*fp2;
printf("Enter the actual starting address : ");
scanf("%d",&start);
start-=1000;
fp1=fopen("relinput.dat","r");
fp2=fopen("reloutput.dat","w");
fscanf(fp1,"%s",input);
while(strcmp(input,"E")!=0)
{
if(strcmp(input,"H")==0)
{ fscanf(fp1,"%s",add);
fscanf(fp1,"%s",length);
fscanf(fp1,"%s",input);
printf(" ADDRESS OBJECT CODE \n");
printf(" \n");
}
if(strcmp(input,"T")==0)
{
fscanf(fp1,"%d",&address);
fscanf(fp1,"%s",bitmask);
address+=start;
len=strlen(bitmask);
for(i=0;i<len;i++)
{
fscanf(fp1,"%d",&opcode);
fscanf(fp1,"%d",&addr);
relocbit=bitmask[i];
if(relocbit=='0')
actualadd=addr;
else
actualadd=addr+start;
fprintf(fp2,"%d\t%d%d\n",address,opcode,actualadd);
address+=3;
}
fscanf(fp1,"%s",input);
}
}
fclose(fp1);
fclose(fp2);

printf("\nreloutput.dat :\n\n");

128
DATE:14/10/2024
EXPERIMENT NO. 9
RELOCATION LOADER

AIM: Implement a Relocation Loader


ALGORITHM:
1. Start the program

2. Include the necessary header file and variable

3. Open the following two file

fp1= relinput.dat
fp2= reloutput.dat.
4. Read the content. Using while loop perform the loop until character is not equal to E.

5. If the character is H then get the variable add, length, and input

6. Else if the character is T then get the variable address and bitmask and perform the for loop starting from
zero and up to len.
7. Get the opcode ,addr and assign relocbit to bitmask.

8. If relocabit is zero then actualadd=addr.

9. Else add the addr and starting value10.

10. Finally terminate the program

129
fp2=fopen("reloutput.dat","r");
ch2=fgetc(fp2);
while(ch2!=EOF)
{
printf("%c",ch2);
ch2=fgetc(fp2);
}
fclose(fp2);
printf("\n");
}
relinput.dat
H 1000 200
T 1000 11001 14 1033 48 1039 90 1776 92 1765 57 1765
T 2011 11110 23 1838 43 1979 89 1060 66 1849 99 1477
E 1000

OUTPUT
Enter the actual starting address : 4000
ADDRESS OBJECT CODE

4000 144033
4003 484039
4006 901776
4009 921765
4012 574765
5011 234838
5014 434979
5017 894060
5020 664849
5023 991477

130
RESULT: The program has been executed successfully and the expected output has been obtained andverified.

131
PROGRAM
16 BIT ADDITION
data segment
msg1 db 0ah,0dh, "Enter first number : $"
msg2 db 0ah,0dh, "Enter second number : $"
msg3 db 0ah,0dh, "Result is : $"
n1 db 07h dup(?)
n2 db 07h dup(?)
data ends
code segment
assume cs:code,ds:data
start: mov ax,data
mov ds,ax

;Getting offset of arrays


mov si,offset n1
mov di,offset n2

;Printing "Enter first number"


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

;Setting Count to 4
mov cl,04h

;Getting First Number


first:mov ah,01h
int 21h
sub al,30h
mov [si],al
inc si
dec cl

132
DATE:14/10/2024

EXPERIMENT NO. 10
DECIMAL ARITHMETIC OPERATION

AIM: Implementation of decimal arithmetic operations (16 bit addition,16 bit subtraction)
ALGORITHM:

START
1. Initialize Data Segment
a) Define messages for prompts and result display.
b) Reserve memory for two input numbers.
2. Set Up Code Segment
a) Set up data segment register.
3. Prompt for First Number
a) Display the message "Enter first number".
b) Initialize a counter for four digits.
c) Loop to read each digit from user input:
▪ Convert character to a number and store it in the first number array.
4. Prompt for Second Number
a) Display the message "Enter second number".
b) Reset the counter for four digits.
c) Loop to read each digit of the second number:
▪ Convert character to a number and store it in the second number array.
5. Add the Two Numbers
a) Set a counter for four digits.
b) Clear any previous carry.
c) Loop through each digit from the end of both arrays:
▪ Add corresponding digits along with carry.
▪ Adjust the result if needed for ASCII representation.
▪ Store each result digit in the result array.
6. Display the Result
a) Print the message "Result is".
b) Check for any remaining carry and display if present.

133
jnz first

;Printing "Enter second number"


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

;Setting count to 4
mov cl,04h

;Getting second Number


second:mov ah,01h
int 21h
sub al,30h
mov [di],al
inc di
dec cl
jnz second

;Clearing carry
clc

;Setting count to 4
mov cl,04h

;Performing Addition
addition:dec di
dec si
mov al,[si]
mov bl,[di]

adc al,bl
mov ah,00h
aaa

134
c) Loop through the result array and display each digit.
7. End Program
END

135
;Storing result to di array
mov [di],al

dec cl
jnz addition

;Printing "Result is"


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

;Printing Result
mov bh,00h
mov dl,30h
adc dl,bh
cmp dl,30h
je skip

;Printing Carry
mov ah,02h
int 21h

skip:
;Setting Count to 4
mov cl,04h

;Printing array content


print:mov dl,[di]
add dl,30h

mov ah,02h
int 21h

inc di

136
137
dec cl
jnz print

mov ah,4ch
int 21h
code ends
end start

OUTPUT
Enter first number : 1234
Enter second number : 3450
Result is : 4684

138
139
16 BIT SUBTRACTION
data segment
msg1 db 0ah, 0dh, "Enter first number: $"
msg2 db 0ah, 0dh, "Enter second number: $"
msg3 db 0ah, 0dh, "Result is: $"
n1 db 07h dup(?)
n2 db 07h dup(?)
data ends
code segment
assume cs:code, ds:data
start:
mov ax, data
mov ds, ax

mov si, offset n1


mov di, offset n2

lea dx, msg1


mov ah, 09h
int 21h

; Setting Count to 4
mov cl, 04h

; Getting First Number


first:
mov ah, 01h
int 21h
sub al, 30h
mov [si], al
inc si
dec cl
jnz first

140
ALGORITHM:
START
1. Initialize Data Segment
a) Define messages for prompts and result display.
b) Reserve memory for two input numbers.
2. Set Up Code Segment
a) Set up the data segment register.
3. Prompt for First Number
a) Display the message "Enter first number".
b) Initialize a counter for four digits.
c) Loop to read each digit from user input:
▪ Convert the character to a number and store it in the first number array.
4. Prompt for Second Number
a) Display the message "Enter second number".
b) Reset the counter for four digits.
c) Loop to read each digit of the second number:
▪ Convert the character to a number and store it in the second number array.
5. Subtract the Second Number from the First
a) Set a counter for four digits.
b) Clear any previous borrow.
c) Loop through each digit from the end of both arrays:
▪ Subtract the corresponding digit of the second number from the first, considering any
borrow.
▪ Adjust the result if needed (e.g., if the result is negative, adjust for borrow).
▪ Store each result digit in the result array.
6. Display the Result
a) Print the message "Result is".
b) Check for any remaining negative results and display as needed.
c) Loop through the result array and display each digit.
7. End Program
END

141
; Printing "Enter second number"
lea dx, msg2
mov ah, 09h
int 21h

; Setting count to 4
mov cl, 04h

; Getting second Number


second:
mov ah, 01h
int 21h
sub al, 30h
mov [di], al
inc di
dec cl
jnz second

; Clearing carry
clc

; Setting count to 4
mov cl, 04h

; Performing Subtraction
subtraction:
dec di
dec si
mov al, [si]
mov bl, [di]

sub al, bl
sbb ah, 0
mov [di], al

142
143
dec cl
jnz subtraction

; Printing "Result is"


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

; Printing Result
mov bh, 00h
mov dl, 30h
adc dl, bh
cmp dl, 30h
je skip

; Printing Carry
mov ah, 02h
int 21h

skip:
; Setting Count to 4
mov cl, 04h

; Printing array content


print:
mov dl, [di]
add dl, 30h

mov ah, 02h


int 21h

inc di
dec cl
jnz print

144
145
mov ah, 4ch
int 21h
code ends
end start

OUTPUT
Enter first number : 8451
Enter second number : 2341
Result is : 6110

146
RESULT: The programs has been executed successfully and the expected output has been obtained and
verified.

147
PROGRAM
PALINDROME
.model small
.stack 100h
.data
string db ?
msg1 db 10,13,"enter the string:$"
msg2 db 10,13,"string is a palindrome$"
msg3 db 10,13,"string is not a palindrome$"
.code
main proc
mov ax,@data
mov ds,ax
lea dx,msg1
mov ah,09
int 21h
lea si,string
input:mov ah,01
int 21h
mov [si],al
cmp al,13
je send
inc si
jne input

send:mov al,'$'
mov [si],al
dec si
lea di,string
find:cmp si,di
jl istrue
mov al,[si]
mov bl,[di]
cmp al,bl
148
DATE:19/10/2024

EXPERIMENT NO. 11
STRING MANIPULATION

AIM: Implementation of string manipulation


1) Palindrome (Check whether the string is palindrome or not)
ALGORITHM:
START
1. Initialize Data Segment
a) Define messages for input prompt and result (palindrome or not).
b) Reserve memory for the input string.
2. Set Up Code Segment
a) Load the data segment.
3. Display Input Prompt
a) Print the message "Enter the string:" to prompt the user.
4. Read Input String
a) Set SI to point to the start of the string.
b) Read characters one by one using int 21h, and store each character at [SI].
c) If the Enter key (ASCII 13) is detected, terminate input.
5. Mark End of String
a) Place the end marker $ at the end of the input string.
b) Move SI to the last character in the string (before the $).
6. Initialize Comparison Pointers
a) Set DI to point to the start of the string.
b) SI points to the last character of the input.
7. Check for Palindrome
a) Loop to compare characters:
▪ Compare characters at [SI] and [DI].
▪ If they do not match, jump to the isfalse label (indicating the string is not a
palindrome).
▪ If they match, increment DI and decrement SI to move towards the center of the string.
b) Continue comparing until SI is less than DI.

149
jne isfalse
inc di
dec si
jmp find
istrue:lea dx,msg2
jmp toend
isfalse:lea dx,msg3
toend:mov ah,09
int 21h
mov ah,4ch
int 21h

main endp
end main

OUTPUT
enter the string:malayalam
string is a palindrome
enter the string:apple
string is not a palindrome

150
8. Display Result
a) If the comparison completes successfully, jump to istrue and print "String is a palindrome."
b) If any mismatch occurs, print "String is not a palindrome."
9. End Program
END

151
VOWEL
.model small
.stack 100h
.data
string db ?
msg db 10,13,"enter the string:$"
msg1 db 10,13, "no of vowels:$"
count db 0
.code
main proc
mov ax,@data
mov ds,ax
mov es,ax
lea dx,msg
mov ah,09
int 21h
lea si,string
mov bl,0
input:mov ah,01
int 21h
mov [si],al
inc si
inc bl
cmp al,13
je t1
jne input
t1:mov al,'$'
mov [si],al
dec bl
lea si,string
mov cl,bl
find:mov al,[si]
inc si
cmp al,'a'

152
2) Vowels (To count the number of vowels in given string)
ALGORITHM:
START
1. Initialize Data Segment
a) Define messages for input prompt and displaying the count of vowels.
b) Reserve memory for the input string and a counter variable (count).
2. Set Up Code Segment
a) Set up the data and extra segments.
3. Display Input Prompt
a) Print the message "Enter the string:" to prompt the user.
4. Read Input String
a) Set SI to point to the start of the string.
b) Use a loop to read each character using int 21h and store it at [SI].
c) Increment the input pointer (SI) and character count (BL).
d) When the Enter key (ASCII 13) is detected, end the input and terminate the loop.
5. Mark End of String
a) Place the $ end marker at the end of the string.
6. Count Vowels in String
a) Set CL to the number of characters entered (in BL).
b) Loop through the string (SI pointer) to check each character:
▪ Compare the character against vowels: 'a', 'e', 'i', 'o', 'u'.
▪ If a vowel is found, increment the count variable.
▪ Continue this until all characters are checked.
7. Display Vowel Count
a) Print the message "No of vowels".
b) Convert the vowel count to ASCII by adding 48 (to display it as a character).
c) Display the count using int 21h.
8. End Program
a) Terminate the program.
END

153
je increase
cmp al,'e'
je increase
cmp al,'i'
je increase
cmp al,'o'
je increase
cmp al,'u'
je increase
dec cl
cmp cl,0
jne find
jmp toend
increase:
inc count
dec cl
cmp cl,0
jne find
toend:lea dx,msg1
mov ah,09
int 21h
mov dl,count
add dl,48
mov ah,02
int 21h
mov ah,4ch
int 21h
main endp
end main

OUTPUT
Enter the string:mango
no of vowels:2

154
RESULT: The programs has been executed successfully and the expected output has been obtained and
verified.

155
PROGRAM
LINEAR SEARCH
.model small
.386

.data
array dd 30 dup(?)
len db ?
num dd ?
str1 db 0ah,"Enter the number of elements: $"
str2 db 0ah,"Enter the array elements: $"
str3 db 0ah,"Enter the item to be searched: $"
str4 db 0ah,"The item found at position: $"
str5 db 0ah,"The item not found: $"

.code
mov ax,@data
mov ds,ax

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

mov ah,01h
int 21h
sub al,30h
mov [len],al

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

lea si,array
mov cl,[len]
read:
mov ebx,0000h
mov ah,01h
int 21h
mov bh,al

int 21h
mov bl,al

rol ebx,16; rotate left operation on ebx register, 16 positions

int 21h
mov bh,al
int 21h
mov bl,al

156
DATE:19/10/2024

EXPERIMENT NO. 12
SEARCHING & SORTING

AIM: Implementation of searching and sorting of 16 bit numbers


1) Linear Search 2) Bubble Sort
ALGORITHM:
START
1. Initialize the array of elements.
2. Prompt the user to enter the number of elements in the array.
3. Read the elements of the array from the user.
4. Prompt the user to enter the item to be searched.
5. Initialize a counter (position) to 1.
6. Start a loop to iterate through the array:
a. Compare the current element with the item to be searched.
b. If the element matches the item:
i. Display the position of the item in the array.
ii. Exit the loop.
c. If the element does not match, increment the counter and continue the loop.
7. If the item was not found after checking all elements, display a "not found" message.
END

157
mov [si],ebx
add si,4; incrementing index register by 4 bytes(because each digit take 1 byte)
mov ah,02h
mov dl," "
int 21h
loop read

lea dx,str3
mov ah,09h
int 21h
;reading the item to be searched
mov ah,01h
int 21h
mov bh,al
int 21h
mov bl,al
rol ebx,16
int 21h
mov bh,al
int 21h
mov bl,al

mov [num],ebx

lea si,array
mov cl,[len]
mov bh,00h
search:
inc bh
mov eax,[si]
.if eax == [num]
lea dx,str4
mov ah,09h
int 21h
mov ah,02h
mov dl,bh
add dl,30h
int 21h
mov ah,4ch
int 21h
.else
add si,4
.endif
loop search

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

mov ah,4ch

158
159
int 21h
end

OUTPUT
Enter the number of elements: 3
Enter the array elements: 1234 5678 3456
Enter the item to be searched: 5678
The item found at position: 2

Enter the item to be searched: 9876


The item not found

160
161
BUBBLE SORT
.model small
.386
.data
array dd 30 dup(?)
len db ?
min dd ?
temp dd ?
str1 db 0ah,"Enter the number of elements: $"
str2 db 0ah,"Enter the array elements: $"
str3 db 0ah,"The sorted array is $"

.code
mov ax,@data
mov ds,ax

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

mov ah,01h
int 21h
sub al,30h
mov [len],al

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

lea si,array
mov cl,[len]
read:
mov ebx,0000h
mov ah,01h

162
ALGORITHM:
START
1. Initialize the array with 30 elements.
2. Display the prompt: "Enter the number of elements".
3. Read the number of elements (n) from the user and store in the variable `len`.
4. Display the prompt: "Enter the array elements".
5. Read `n` elements from the user and store them in the array:
a. For each element:
i. Read the element from the user.
ii. Store the element in the array.
6. Perform Bubble Sort on the array:
a. For i = 1 to n-1 (outer loop for each pass):
i. For j = 0 to n-i-1 (inner loop comparing adjacent elements):
- If the current element (array[j]) is greater than the next element (array[j+1]):
- Swap the elements.
b. Repeat until the array is sorted.
7. Display the sorted array:
a. For each element in the array:
i. Print the element.
END

163
int 21h
mov bh,al

int 21h
mov bl,al

rol ebx,16

int 21h
mov bh,al

int 21h
mov bl,al

mov [si],ebx
add si,4
mov ah,02h
mov dl," "
int 21h
loop read

lea si,array
mov cl,[len]
; Using Bubble Sort
sort:
lea si,array
mov bh,[len]
.while bh > 1
mov eax,[si]
.if eax > [si+4]
mov [temp],eax
mov eax,[si+4]
mov [si],eax
mov eax,[temp]

164
165
mov [si+4],eax
.endif
add si,4
dec bh
.endw
loop sort

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

;Displaying the sorted array


lea si,array
mov cl,[len]
mov ah,02h
display:
mov ebx,[si]
mov ch,04h
.while ch > 0
rol ebx,8
mov dl,bl
int 21h
dec ch
inc si
.endw
mov ah,02h
mov dl," "
int 21h
loop display

mov ah,4ch
int 21h
end

166
167
OUTPUT
Enter the number of elements: 4
Enter the array of elements: 2222 1111 8888 6543
The sorted array is 1111 2222 6543 8888

168
RESULT: The programs has been executed successfully and the expected output has been obtained and
verified.

169
PROGRAM:
MEMORY OPCODE MNEMONICS
ADDRESS
0400 25 AND AX,0000
0401 00 -
0402 00 -
0403 BB MOV BX,0600
0404 00 -
0405 06 -
0406 BE MOV SI,0500
0407 00 -
0408 05 -
0409 BF MOV DI,0550
040A 50 -
040B 05 -
040C 8B MOV AX,[SI]
040D 04 -
040E 03 ADD AX,[DI]
040F 05 -
0410 89 MOV [BX],AX
0411 07 -
0412 B8 MOV AX,0000
0413 00 -
0414 00 -
0415 15 ADC AX,0000
0416 00 -
0417 00 -
0418 89 MOV
[BX+2],AX
0419 47 -

170
DATE:-06/11/2024

EXPERIMENT NO : 13
ADDITION USING 8086

AIM:
Write an assembly language program to perform addition of two 16-bit numbers

THEORY & PROCEDURE:


Clear the carry flag & the memory location 0900 to BX & 0700 to source index register. The
numbers from memory to AX and BX register, then add them using ADD instruction. When the
Carry is present, store carry into memory, otherwise only store AX into memory. Stop the program
execution.

EXECUTION:
Enter the opcode values in the memory location and enter the input values in separate memory
locations. Press the Go key and give the starting address 0400 then press EXEC and RESET. Then
DISPLAY the result.

ALGORITHM:
1. Clear the accumulator
2. Initialise segment register & index register
3. Move 1st number to Accumulator
4. Add 1st & 2nd number, store result in destination address
5. Increment address pointer by two and store carry if any, in next destination address
6. Stop

171
041A 02 -

041B F4 HLT

OUTPUT:

INPUT OUTPUT
0500 - B5 0600 - DR
0501 - 7A 0601 - 5F
0550 - 2A 0602 - 01
0551 - E5

172
RESULT:The program has been executed successfully and the expected output has been obtained and
verified.

173
PROGRAM:
MEMORY OPCODE MNEMONICS
ADDRESS

0400 F8 CLC

0401 BB MOV BX,0900

0402 00 -

0403 09 -

0404 BE MOV SI,0700

0405 00 -

0406 07 -

0407 BF MOV DI,0800

0408 00 -

0409 08 -

040A 8B MOV AX,[SI]

040B 04 -

040C 1B SBB AX,[DI]

040D 05 -

040E 89 MOV BX,[AX]

040F 07 -

0410 F4 HLT

OUTPUT:
INPUT OUTPUT
0700 - 18 0900 - D8
0701 - 08 0901 - F7
0800 - 40
0801 - 10

174
DATE:-06/11/2024
EXPERIMENT NO : 13(B)
SUBTRACTION USING 8086

AIM:
Write an assembly language program to perform addition of two 16-bit numbers

THEORY & PROCEDURE:


Clear the carry flag and the memory location 0900 to BX and 0700 to source index register and
also move the memory content of SI to AX register. Subtract the SI register now move the AX
register to BX memory content. Stop the program execution.

EXECUTION:
Enter the opcode values in the memory location and enter the input values in separate memory
location. Press the Go key and give the starting address 0400 then press EXEC and RESET. Then
DISPLAY the result.

ALGORITHM:
1. Clear the carry.
2. Initialize the index register with required memory.
3. Subtract accumulator content fromsubtrahend and store the result.
4. Stop

RESULT:The program has been executed successfully and the expected output has been obtained and
verified.

175
PROGRAM:
MEMORY OPCODE MNEMONICS
ADDRESS

0400 F8 CLC

0401 BB MOV BX,0700

0402 00 -

0403 07 -

0404 BE MOV SI,0750

0405 50 -

0406 07 -

0407 BF MOV DI,0800

0408 00 -

0409 08 -

040A 8B MOV AX,[SI]

040B 04 -

040C 8B MOV CX,[DI]

040D 00 -

040E F7 MUL CX

040F E1 -

0410 89 MOV [BX],AX

0411 07 -

0412 43 INC BX

0413 43 INC BX

0414 89 MOV [BX],DX

0415 17 -

0416 F4 HLT

176
DATE:-06/11/2024
EXPERIMENT NO : 13(C)
MULTIPLICATION USING 8086

AIM:
Write an assembly language program to perform multiplication of two 16-bit numbers

THEORY & PROCEDURE:


Clear the carry flag and move the memory location 0700 to BX and 0750 to source index register
and also move the memory content of destination index to CX register. Multiply the CX register
and now move the AX register to BX memory content. Increment BX register twice, move the AX
register to BX memory content .Stop the program execution.

EXECUTION:
Enter the opcode values in the memory location and enter the input values in separate memory
locations. Press the Go key and give the starting address 0400 then press EXEC and RESET. Then
DISPLAY the result.

ALGORITHM:
1. Clear the carry.
2. Initialize the index register with the required address.
3. Move the first number to Accumulator.
4. Move the second number to CX.
5. Multiply the two numbers.
6. Store the result.

177
OUTPUT:

INPUT OUTPUT
0750 - 1A 0700 - 9E
0751 - 2B 0701 - 74
0800 - 4B 0702 – 14
0801 - 12 0703 - 03

178
RESULT:The program has been executed successfully and the expected output has been obtained and
verified.

179
PROGRAM:

MEMORY OPCODE MNEMONICS


ADDRESS

0400 F8 CLC

0401 BB MOV BX,0700

0402 00 -

0403 07 -

0404 BE MOV SI,0750

0405 50 -

0406 07 -

0407 BF MOV DI,0800

0408 00 -

0409 08 -

040A 8B MOV AX,[SI]

040B 04 -

040C 8B MOV CX,[DI]

040D 0D -

040E B5 MOV CH,00

040F 00 -

0410 F6 DIV CL

0411 F1 -

0412 89 MOV [BX],AX

0413 07 -

0414 F4 HLT

180
DATE:-06/11/2024
EXPERIMENT NO : 13(D)
DIVISION USING 8086

AIM:
Write an assembly language program to perform division of two 16-bit numbers

THEORY & PROCEDURE:


Clear the carry flag and move the memory location 0700 to 16 bit BX register then move the
memory location 0750 to source index register and also move the memory content of source index
to 16 bit AX register.Now move the content of source index to 8-bit CL register moves the 16 bit
AX. Now move the memory location 00 to 8 bit CH register. Now perform the division operation
with 8 bit CL register. Move the 16 bit AX register to memory content of the 16 bit BX
register.Stop the program execution.

EXECUTION:
Enter the hexadecimal values and give the input in the separate memory location. Press Go key
and type the starting address then EXEC where the result is stored.

ALGORITHM:
1. Clear the carry.
2. Initialize the index register
3. Move dividend to accumulator and add divisor to CX.
4. Perform Division.
5. Store the result.

181
OUTPUT:

INPUT OUTPUT
0750 - 43 0700 - 8D
0751 - 12 0701 - 16
0800 - 21

182
RESULT:The program has been executed successfully and the expected output has been obtained and
verified.

183
PROGRAM:

MEMORY OPCODE MNEMONICS COMMENT


ADDRESS

8000 90,81,00 MOVDPTR, Set Source Address


#8100

8003 E0 MOVX A,@DPTR Get First Byte

8004 F8 MOV R0,A Store temporarily

8005 A3 INC DPTR Increment pointer to


get next byte

8006 E0 MOVX A,@DPTR Get Next Byte

8007 28 ADD A,R0 Add

8008 A3 INC DPTR Increment pointer to


store Result

8009 F0 MOVX @DPTR,A Store LSB of


Result

800A 74,00 MOV A,#00 -

800C 34,00 ADDC A,#00 Add to get carry

800E A3 INC DPTR Increment pointer to


store MSB Result

800F F0 MOVX @DPTR,A Store MSB of


Result

8010 02,80,10 LJMP 8010 Wait here

OUTPUT:
INPUT OUTPUT
8100-15 8102-1F
8101-0A 8103-00

184
DATE:-06/11/2024
EXPERIMENT NO : 14(A)
ADDITION USING 8051

AIM:
Write an assembly language program to add two 8-bit numbers.

ALGORITHM:
1. Set Source Address.
2. Get First Byte
3. Store temporarily
4. Increment pointer to get the next byte.
5. Get Next Byte.
6. Add.
7. Increment pointer to store Result.
8. Store LSB of Result.
9. Add to get carry.
10. Increment pointer to store MSB Result.
11. Store MSB of Result..
12. Stop.

RESULT:The program has been executed successfully and the expected output has been obtained and
verified.

185
PROGRAM:
MEMORY OPCODE MNEMONICS COMMENT
ADDRESS

8000 90,81,00 MOVDPTR, Set Source Address


#8100

8003 E0 MOVX A,@DPTR Get First Byte

8004 F8 MOV R0,A Store temporarily

8005 A3 INC DPTR Increment pointer to


get next byte

8006 E0 MOVX A,@DPTR Get Next Byte

8007 A3 INC DPTR Increment pointer to


store Result

8008 C3 CLR C Clear carry Before


Subtraction

8009 98 SUBB A,R0 Subtract

800A F0 MOVX @DPTR,A Store LSB of


Result

800B A3 INC DPTR Increment pointer to


store MSB Result

800C 74,00 MOV A,#00 -

800E 34,00 ADDC A,#00 Add to get Borrow

8010 F0 MOVX @DPTR,A Store Borrow of


Result

8011 02,80,11 LJMP 8011 Wait here

OUTPUT:
INPUT OUTPUT
8100-15 8102-13
8101-02 8103-00

186
DATE:-06/11/2024
EXPERIMENT NO: 14(B)
SUBTRACTION USING 8051
AIM:

Write an assembly language program to subtract two 8-bit numbers.

ALGORITHM:
1. Set source address.
2. Get the first byte.
3. Store temporarily.
4. Increment pointer to get the next byte.
5. Get the next byte.
6. Increment pointer to store result.
7. Clear carry before subtraction.
8. Subtract.
9. Store LSB of Result.
10. Increment pointer to store MSB result.
11. Add to get borrow.
11. Store borrow of result.
12. Stop.

RESULT:The program has been executed successfully and the expected output has been obtained and
verified.

187
PROGRAM:

MEMORY OPCODE MNEMONICS COMMENT


ADDRESS

8000 90,81,00 MOVDPTR, Set Source Address


#8100

8003 E0 MOVX A,@DPTR Get First Byte

8004 F5,F0 MOV F0,A Store temporarily

8006 A3 INC DPTR Increment pointer to


get next byte

8007 E0 MOVX A,@DPTR Get Next Byte

8008 A4 MUL AB Multiply

8009 A3 INC DPTR Increment pointer to


store LSB of Result

800A F0 MOVX @DPTR,A Store LSB of


Result

800B E5,F0 MOV A,F0 -

800D A3 INC DPTR Increment pointer to


store MSB Result

800E F0 MOVX @DPTR,A Store MSB of


Result

800F 02,80,0F LJMP 800F Wait here

OUTPUT:

INPUT OUTPUT
8100-15 8102-2A
8101-02 8103-00

188
DATE:-06/11/2024
EXPERIMENT NO : 14(C)
MULTIPLICATION USING 8051
AIM:
Write an assembly language program to multiply two numbers.

ALGORITHM:
1. Set source address.
2. Get the first byte.
3. Store temporarily.
4. Increment pointer to get the next byte.
5. Get the next byte.
6. Multiply.
7. Increment pointer to store LSB of result.
8. Store LSB of Result.
9. Increment pointer to store MSB result.
10. Store MSB of results.
11. Stop.

RESULT:The program has been executed successfully and the expected output has been obtained and
verified.

189
PROGRAM:

MEMORY OPCODE MNEMONICS COMMENT


ADDRESS

8000 90,81,00 MOVDPTR, Set Source Address


#8100

8003 E0 MOVX A,@DPTR Get First Byte

8004 F5,F0 MOV F0,A Store temporarily

8006 A3 INC DPTR Increment pointer to


get next byte

8007 E0 MOVX A,@DPTR Get Next Byte

8008 84 DIV AB Divide

8009 A3 INC DPTR Increment pointer to


store Quotient

800A F0 MOVX @DPTR,A Store Quotient

800B E5,F0 MOV A,F0 -

800D A3 INC DPTR Increment pointer


to store Remainder
of Result

800E F0 MOVX @DPTR,A Store Remainder of


Result

800F 02,80,0F LJMP 800F Wait here

OUTPUT:

INPUT OUTPUT
8100-15 8102-0A
8101-02 8103-01

190
DATE:-06/11/2024
EXPERIMENT NO : 14(D)
DIVISION USING 8051

AIM:
Write an assembly language program to divide two 8-bit numbers.

ALGORITHM:
1. Set source address.
2. Get the first byte.
3. Store temporarily.
4. Increment pointer to get the next byte.
5. Get the next byte.
6. Divide.
7. Increment pointer to store quotient.
8. Store quotient.
9. Increment pointer to store remainder of result.
10. Store the remainder of the result.
11. Stop.

RESULT:The program has been executed successfully and the expected output has been obtained and
verified.

191
PROGRAM:
MEMORY LABEL MNEMONICS COMMENT
ADDRESS

1000 START MOV DI,2000 MOVE THE HEXADECIMAL 2000

1004 MOV CL,04 MOVE COUNT TO CL

1007 LOOP1 MOV AL,[DI] MOVE CONTENT OF DI INFO

1009 OUT C0,AL OUTPUT THE DATA

100B MOV DX,1010 LOAD THE DISPLACEMENT


VALUE TO DX

100F DELAY DEC DX DECREMENT DX

1010 JNZ 100F IF NOT ZERO

1012 INC DI INCREMENT DI

1013 LOOP 1007 LOOP THE STATEMENT

1015 JMP 1000 JUMP TO START

INPUT:

2000 05 09

2002 06 0A

192
DATE:-06/11/20224
EXPERIMENT NO : 15
STEPPER MOTOR

AIM:

Write an assembly language program to rotate a stepper motor in clockwise direction

ALGORITHM:
1. Set source pointer

2. Set count value

3. Set delay

4. Output the value until CX=1

5. Repeat from 1

RESULT:The program has been executed successfully and the expected output has been obtained and
verified.

193

You might also like