0% found this document useful (0 votes)
23 views

LP-1 Practical Code & Output

Uploaded by

Janhavi Kongari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

LP-1 Practical Code & Output

Uploaded by

Janhavi Kongari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Experiment 1

Design suitable Data Structures and implement Pass-I and Pass-II of a two-pass
assembler for pseudo-machine. Implementation should consist of a few instructions from
each category and few assembler directives. The output of Pass-I (intermediate code file
and symbol table) should be input for Pass-II.

Pass1.java
Code:
package Tools;
import java.util.*;
import java.io.*;
public class pass1 {

public static void main(String args[]) throws FileNotFoundException,Exception{

String line="",line2="";
Map data=new HashMap();
data.put("DS", "001");
data.put("Dc", "002");
System.out.println("DATA TABLE:"+data);

Map mnemonic=new HashMap();


mnemonic.put("ADD", "01");
mnemonic.put("SUB", "02");
mnemonic.put("MUL", "03");
mnemonic.put("DIV", "04");
mnemonic.put("MOVER", "05");
mnemonic.put("MOVEM", "06");
System.out.println("MNEMONIC TABLE:"+mnemonic);

Map directive=new HashMap();


directive.put("START", "11");
directive.put("END","12");
System.out.println("DIRECTIVE TABLE:"+directive);

Map condition=new HashMap();


condition.put("LT", "21");
condition.put("GT", "22");
condition.put("LTE", "23");
condition.put("GTE", "24");
condition.put("EQU", "25");
System.out.println("CONDITION TABLE:"+condition);

Map Register=new HashMap();


Register.put("AREG", "31");
Register.put("BREG", "32");
Register.put("CREG", "33");
Register.put("DREG", "34");
System.out.println("REGISTER TABLE:"+Register);
Map Symbol=new HashMap();
Map lit_table=new HashMap();

BufferedReader br =new BufferedReader(new FileReader("/home/stes/eclipse-


workspace/input.txt"));
String split_words[] = new String[5] ;
String c;
int counter = 100;
int coun1= 0;
int coun2=0;

while(( c = br.readLine()) != null)


{
split_words = c.split("\t");
System.out.println("\n"+c);
if(split_words.length>4)
{
System.out.println("more than 4 words not allowed");
}
try
{
if(split_words[0] != null)
{
if(Symbol.containsKey(split_words[0]))
{
System.out.print(Symbol.get(split_words[0]));
Symbol.put(split_words[0],Integer.toString(coun2));
}
}
if(split_words[1] != null)
{
if(directive.containsKey(split_words[1]))
{
System.out.println("\t");
}
if(mnemonic.containsKey(split_words[1]))
{
System.out.print("\t"+mnemonic.get(split_words[1]));
}
if(Symbol.containsKey(split_words[1]))
{
if(split_words[2]=="DS")
{
counter=counter+Integer.parseInt(split_words[2]);
}
}
if(split_words[2] != null)
{
if(split_words[1] == "START")
{
counter = Integer.parseInt(split_words[2]);
}
if(Register.containsKey(split_words[2]))
{
System.out.print("\t"+Register.get(split_words[2]));
}
}
if(split_words[3] != null)
{
if(split_words[3].startsWith("="))
{
coun1++;
lit_table.put(split_words[3], Integer.toString(coun1));
System.out.println("\tL"+lit_table.get(split_words[3]));
}
else
{
if(Symbol.containsKey(split_words[3]))
{
System.out.print("\tS"+Symbol.get(split_words[3]));
}
else
{
coun2++;
Symbol.put(split_words[3],Integer.toString(coun2));
System.out.print("\tS"+Symbol.get(split_words[3]));
}
}
}
}
}
catch(Exception e)
{
continue;
}
counter++;
System.out.println("\n");
} //end while
System.out.println(line);
System.out.println("SYMBOL TABLE:"+Symbol);
System.out.println("Literal TABLE:"+lit_table);
}
}

Input.txt
START 200
B ADD AREG =10
MUL BREG A
A DS 2
END
Ouput:
DATA TABLE:{DS=001, Dc=002}
MNEMONIC TABLE:{DIV=04, ADD=01, SUB=02, MOVER=05, MUL=03, MOVEM=06}
DIRECTIVE TABLE:{START=11, END=12}
CONDITION TABLE:{LT=21, EQU=25, GTE=24, LTE=23, GT=22}
REGISTER TABLE:{DREG=34, AREG=31, BREG=32, CREG=33}
START 200
B ADD AREG =10
01 31 L1
MUL BREG A
03 32 S1
A DS 2
1
END

SYMBOL TABLE:{A=1}
Literal TABLE:{=10=1}

DATA TABLE:{DS=001, Dc=002}


MNEMONIC TABLE:{DIV=04, ADD=01, SUB=02, MOVER=05, MUL=03, MOVEM=06}
DIRECTIVE TABLE:{START=11, END=12}
CONDITION TABLE:{LT=21, EQU=25, GTE=24, LTE=23, GT=22}
REGISTER TABLE:{DREG=34, AREG=31, BREG=32, CREG=33}
START 100
L1 MOVER AREG =3
MOVEM BREG X
SUB AREG=1
LTORG
MOVEM AREG Y
BC any L1
ADD CREG,4
X DC 6
Y DS 2
END
SYMBOL TABLE:{}
Literal TABLE:{}
Pass2.java
Code:
package Tools;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.lang.*;
public class pass2 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new
FileReader("/home/stes/eclipse-workspace/Janhavi/src/input3.txt"));
BufferedReader sy = new BufferedReader(new
FileReader("/home/stes/eclipse-workspace/Janhavi/src/sym.txt"));
BufferedReader sy1 = new BufferedReader(new
FileReader("/home/stes/eclipse-workspace/Janhavi/src/sym.txt"));
BufferedReader sy2 = new BufferedReader(new
FileReader("/home/stes/eclipse-workspace/Janhavi/src/sym.txt"));
BufferedReader li = new BufferedReader(new FileReader("/home/stes/eclipse-
workspace/Janhavi/src/lit.txt"));
String split_words[] = new String[5] ;
String sym_words[] = new String[5] ;
String lit_words[] = new String[5] ;
String check;

int addr;
String c;
String d;
String e,f;
int counter = 100;
int Dscounter;
c=br.readLine();
split_words=c.split(" ");
/*counter=Integer.parseInt(split_words[1]);*/
// Replace the problematic line with error handling
try {
counter = Integer.parseInt(split_words[1]);
} catch (NumberFormatException e1) {
// Handle the case where split_words[1] is not a valid integer
System.err.println("Invalid integer format: " + split_words[1]);
// Optionally, set a default value or handle this case based on your logic
}
System.out.println(split_words[0]+"\t"+split_words[1]+"\t"+split_words[2]+"\n");
while(( c = br.readLine()) != null)
{
split_words=c.split(" ");
counter++;
System.out.print(counter+"\t");
System.out.println(split_words[0]+"\t"+split_words[1]+"\t"+split_words[2]);
if(split_words[2].startsWith("S"))
{
System.out.print(counter+"\t");
System.out.print(split_words[0]+"\t"+split_words[1]+"\t"+split_words[2]+"\t");
while(( d = sy.readLine()) != null)
{ sym_words = d.split(" ");
if(split_words[2].equals(sym_words[0]))
{ System.out.println(sym_words[2]+"\n");
break;
}
}
}
else if(split_words[2].startsWith("L"))
{ System.out.print(counter+"\t");
System.out.print(split_words[0]+"\t"+split_words[1]+"\t"+split_words[2]);
while(( e = li.readLine()) != null)
{
lit_words = e.split(" ");
if(split_words[2].equals(lit_words[0]))
{
System.out.println("\t"+lit_words[0]+"\n");
break;
}
}
}
else if(split_words[1].contentEquals("DC"))
{
while(( f = sy1.readLine()) != null)
{
sym_words = f.split(" ");
System.out.print("\n");
System.out.print(counter+"\t");
if(split_words[0].equals(sym_words[1]))
{
System.out.print("\t");
System.out.print(sym_words[2]+"\t");
System.out.print("00"+"\t");
System.out.print(split_words[2]+"\n");
break;
}
}
}
else if(split_words[1].contentEquals("DS"))
{
while(( f = sy2.readLine()) != null)
{
sym_words = f.split(" ");
if(split_words[0].equals(sym_words[1]))
{
System.out.print(counter+"\t");
System.out.print(sym_words[2]+"\t");
System.out.print("00"+"\t");
System.out.print(split_words[2]);
/*Dscounter=Integer.parseInt(split_words[2]);
counter=counter+Dscounter-1;
*/
break;
}
}
}

else
{
System.out.println("\n"+"inside else");
System.out.print("\n"+counter+"\t");
System.out.println(split_words[0]+"\t"+split_words[1]+"\t"+split_words[2]);
}

}
}
}

Input3.txt
DATA TABLE:{DS=001, Dc=002}
MNEMONIC TABLE:{MOVEM=06, SUB=02, DIV=04, MUL=03, MOVER=05, ADD=01}
DIRECTIVE TABLE:{START=11, END=12}
CONDITION TABLE:{EQU=25, GT=22, LT=21, LTE=23, GTE=24}
REGISTER TABLE:{CREG=33, DREG=34, BREG=32, AREG=31}

START 200

B ADD AREG =10


01 31 L1

MUL BREG A
03 32 S1

A DS 2
1
END

SYMBOL TABLE:{A=1}
Literal TABLE:{=10=1}

Lit.txt
L0 304
L1 305
L2 306

Sym.txt
S0 ABC 503
S1 lmn 504
S3 pqr 508

Output:
Invalid integer format: TABLE:{DS=001,
DATA TABLE:{DS=001, Dc=002}
101 MNEMONIC TABLE:{MOVEM=06, SUB=02,
101 MNEMONIC TABLE:{MOVEM=06, SUB=02, 102 DIRECTIVE
TABLE:{START=11, END=12}
inside else
102 DIRECTIVE TABLE:{START=11, END=12}
103 CONDITION TABLE:{EQU=25, GT=22,
inside else
103 CONDITION TABLE:{EQU=25, GT=22,
104 REGISTER TABLE:{CREG=33, DREG=34,
inside else
104 REGISTER TABLE:{CREG=33, DREG=34,
105 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 1 out of bounds for length 1
at Tools.pass2.main(pass2.java:48)
Experiment 2
Design suitable data structures and implement Pass-I and Pass-II of a two-pass
macroprocessor. The output of Pass-I (MNT, MDT and intermediate code file without any
macro definitions) should be input for Pass-II.
Pass 1
Code:
import java.io.BufferedReader;
import java.io.FileReader; import
java.io.FileWriter; import
java.io.IOException; import
java.util.Iterator;
import java.util.LinkedHashMap;

public class MacroPass1 {

public static void main(String[] args) throws IOException{


BufferedReader br=new BufferedReader(new
FileReader("macro_input.asm"));

FileWriter mnt=new FileWriter("mnt.txt");


FileWriter mdt=new FileWriter("mdt.txt");
FileWriter kpdt=new FileWriter("kpdt.txt");
FileWriter pnt=new FileWriter("pntab.txt");
FileWriter ir=new FileWriter("intermediate.txt");
LinkedHashMap<String, Integer> pntab=new LinkedHashMap<>();
String line;
String Macroname = null;
int mdtp=1,kpdtp=0,paramNo=1,pp=0,kp=0,flag=0;
while((line=br.readLine())!=null)
{

String parts[]=line.split("\\s+");
if(parts[0].equalsIgnoreCase("MACRO"))
{
flag=1;
line=br.readLine();
parts=line.split("\\s+");
Macroname=parts[0];
if(parts.length<=1)
{

mnt.write(parts[0]+"\t"+pp+"\t"+kp+"\t"+mdtp+"\t"+(kp==0?kpdtp:(kpdtp+1))+"\n");
continue;
}
for(int i=1;i<parts.length;i++) //processing of parameters
{
parts[i]=parts[i].replaceAll("[&,]", "");
//System.out.println(parts[i]);
if(parts[i].contains("="))
{
++kp;
String keywordParam[]=parts[i].split("=");
pntab.put(keywordParam[0], paramNo++);
if(keywordParam.length==2)
{

kpdt.write(keywordParam[0]+"\t"+keywordParam[1]+"\n");
}
else
{
kpdt.write(keywordParam[0]+"\t-\n");
}
}
else
{

pntab.put(parts[i], paramNo++);
pp++;
}
}

mnt.write(parts[0]+"\t"+pp+"\t"+kp+"\t"+mdtp+"\t"+(kp==0?kpdtp:(kpdtp+1))+"\n");
kpdtp=kpdtp+kp;
//System.out.println("KP="+kp);

}
else if(parts[0].equalsIgnoreCase("MEND"))
{
mdt.write(line+"\n");
flag=kp=pp=0;
mdtp++;
paramNo=1;
pnt.write(Macroname+":\t");
Iterator<String> itr=pntab.keySet().iterator();
while(itr.hasNext())
{
pnt.write(itr.next()+"\t");
}
pnt.write("\n");
pntab.clear();
}
else if(flag==1)
{
for(int i=0;i<parts.length;i++)
{
if(parts[i].contains("&"))
{
parts[i]=parts[i].replaceAll("[&,]", "");
mdt.write("(P,"+pntab.get(parts[i])+")\t");
}
else
{
mdt.write(parts[i]+"\t");
}
}

mdt.write("\n");
mdtp++;
}
else
{
ir.write(line+"\n");
}
}
br.close();
mdt.close();
mnt.close();
ir.close();
pnt.close();
kpdt.close();
System.out.println("Macro Pass1 Processing done .................. )");
}

Output:
Macro Pass1 Processing done ................ )

Macro Pass1 file

Macro Input
MACRO
M1 &X, &Y, &A=AREG,
&B=MOVER &A, &X
ADD &A, ='1'
MOVER &B,
&YADD &B,
='5' MEND
MACRO
M2 &P, &Q, &U=CREG, &V=DREG
MOVER &U, &P
MOVER &V,
&QADD &U,
='15'
ADD &V, ='10'
MEND
START 100
M1 10, 20, &B=CREG
M2 100, 200, &V=AREG, &U=BREG
END
Intermediate

START 100
M1 10, 20, &B=CREG
M2 100, 200, &V=AREG, &U=BREG
END
MDT

MOVER (P,3) (P,1)


ADD (P,3) ='1'
MOVER (P,4) (P,2)
ADD (P,4) ='5'
MEND
MOVER (P,3) (P,1)
MOVER (P,4) (P,2)
ADD (P,3) ='15'
ADD (P,4) ='10'
MEND

MNT

M1 2 2 1 1
M2 2 2 6 3

PNTAB

M1: X Y A B
M2: P Q U V
Pass 2
Code:

import java.io.BufferedReader;
import java.io.FileReader; import
java.io.FileWriter; import
java.util.HashMap; import
java.util.Vector;

class MNTEntry {
String name;
int pp,kp,mdtp,kpdtp;
public MNTEntry(String name, int pp, int kp, int mdtp, int kpdtp) {
super();
this.name = name;
this.pp = pp; this.kp
= kp; this.mdtp =
mdtp; this.kpdtp =
kpdtp;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPp() {
return pp;
}
public void setPp(int pp) {
this.pp = pp;
}
public int getKp() {
return kp;
}
public void setKp(int kp) {
this.kp = kp;
}
public int getMdtp() {
return mdtp;
}
public void setMdtp(int mdtp) {
this.mdtp = mdtp;
}
public int getKpdtp() {
return kpdtp;
}
public void setKpdtp(int kpdtp) {
this.kpdtp = kpdtp;
}
}

public class MacroPass2 {


public static void main(String[] args) throws Exception {
BufferedReader irb=new BufferedReader(new FileReader("intermediate.txt"));
BufferedReader mdtb=new BufferedReader(new FileReader("mdt.txt"));
BufferedReader kpdtb=new BufferedReader(new FileReader("kpdt.txt"));
BufferedReader mntb=new BufferedReader(new FileReader("mnt.txt"));

FileWriter fr=new FileWriter("pass2.txt");

HashMap<String, MNTEntry> mnt=new HashMap<>();


HashMap<Integer, String> aptab=new HashMap<>();
HashMap<String,Integer> aptabInverse=new HashMap<>();

Vector<String>mdt=new Vector<String>();
Vector<String>kpdt=new Vector<String>();

int pp,kp,mdtp,kpdtp,paramNo;
String line;
while((line=mdtb.readLine())!=null)
{
mdt.addElement(line);
}
while((line=kpdtb.readLine())!=null)
{
kpdt.addElement(line);
}
while((line=mntb.readLine())!=null)
{
String parts[]=line.split("\\s+");
mnt.put(parts[0], new MNTEntry(parts[0], Integer.parseInt(parts[1]),
Integer.parseInt(parts[2]), Integer.parseInt(parts[3]), Integer.parseInt(parts[4])));

while((line=irb.readLine())!=null)
{
String []parts=line.split("\\s+");
if(mnt.containsKey(parts[0]))
{
pp=mnt.get(parts[0]).getPp();
kp=mnt.get(parts[0]).getKp();
kpdtp=mnt.get(parts[0]).getKpdtp();
mdtp=mnt.get(parts[0]).getMdtp();
paramNo=1;
for(int i=0;i<pp;i++)
{
parts[paramNo]=parts[paramNo].replace(",", "");
aptab.put(paramNo, parts[paramNo]);
aptabInverse.put(parts[paramNo], paramNo);
paramNo++;
}
int j=kpdtp-1;
for(int i=0;i<kp;i++)
{
String temp[]=kpdt.get(j).split("\t");
aptab.put(paramNo,temp[1]);
aptabInverse.put(temp[0],paramNo);
j++;
paramNo++;
}

for(int i=pp+1;i<parts.length;i++)
{
parts[i]=parts[i].replace(",", "");
String splits[]=parts[i].split("=");
String name=splits[0].replaceAll("&", "");
aptab.put(aptabInverse.get(name),splits[1]);
}
int i=mdtp-1;
while(!mdt.get(i).equalsIgnoreCase("MEND"))
{
String splits[]=mdt.get(i).split("\\s+");
fr.write("+");
for(int k=0;k<splits.length;k++)
{
if(splits[k].contains("(P,"))
{
splits[k]=splits[k].replaceAll("[^0-9]",
"");//not containing number
String
value=aptab.get(Integer.parseInt(splits[k]));
fr.write(value+"\t");
}
else
{
fr.write(splits[k]+"\t");
}
}

fr.write("\n");
i++;
}

aptab.clear();
aptabInverse.clear();
}
else
{
fr.write(line+"\n");
}

fr.close();
mntb.close();
mdtb.close();
kpdtb.close();
irb.close();
System.out.println("Macro Pass2 Processing done ........................ )");
}}
Output:
Macro Pass2 Processing done ..................... )

Macro Pass2 file-

Macro Input
MACRO
M1 &X, &Y, &A=AREG,
&B=MOVER &A, &X
ADD &A, ='1'
MOVER &B,
&YADD &B,
='5' MEND
MACRO
M2 &P, &Q, &U=CREG,
&V=DREGMOVER &U, &P
MOVER &V,
&QADD &U,
='15'
ADD &V,
='10'MEND
START 100
M1 10, 20, &B=CREG
M2 100, 200, &V=AREG,
&U=BREGEND
Intermediate

START 100
M1 10, 20, &B=CREG
M2 100, 200, &V=AREG,
&U=BREGEND
Pass2

START 100
+MOVER AREG 10
+ADD AREG ='1'
+MOVER CREG 20
+ADD CREG ='5'
+MOVER BREG 100
+MOVER AREG 200
+ADD BREG ='15'
+ADD AREG
='10'END
Experiment 3
Problem Statement:
Write a program to create a Dynamic Link Library for any mathematical operations
(arithmetic, trigonometric and string operation) and write an application program to test
it. (Java Native Interface/ Use VB/VC++)
Code:
import
java.util.Scanner;
public class JNI {
public native void JniAdd(int no1,int
no2);
public native void JniSub(int no1,int
no2); public native void JniMult(int
no1,int no2);
public native void JniDiv(double no1,double
no2);public native void JniPow(int no1,int
no2);
public native void JniSqrt(int no1);
public native void JniMod(int no1,int
no2);static {
System.load("C:\\Users\\Janhavi
Kongari\\Desktop\\Practical\\LP1\\DLL\\libJNI.dll");}
public static void main(String[] args)throws
Exception {int no1,no2;
Scanner in =new
Scanner(System.in);JNI MJ=new
JNI();
System.out.println("JNI using C");
System.out.print("Enter first
number: ");no1=in.nextInt();
double no1f=no1;
System.out.print("Enter second number:
");no2=in.nextInt();
MJ.JniAdd(no1,no2);
MJ.JniSub(no1,no2);
MJ.JniMult(no1,no2);
MJ.JniDiv((double)no1,(double)n
o2);MJ.JniPow(no1,no2);
MJ.JniSqrt(no2);
MJ.JniMod(no1,no2);
}
}

C File_JNI.h
/* DO NOT EDIT THIS FILE - it is machine
generated */#include <jni.h>
/* Header for class JNI_JNI */
#ifndef
_Included_JNI_JNI
#define
_Included_JNI_JNI
#ifdef cplusplus
extern
"C" {
#endif
/*
* Class: JNI_JNI
* Method: JniAdd
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_JNI_JNI_JniAdd(JNIEnv *, jobject, jint,
jint);
/*
* Class: JNI_JNI
* Method: JniSub
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_JNI_JNI_JniSub(JNIEnv *, jobject, jint,
jint);
/*
* Class: JNI_JNI
* Method: JniMult
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_JNI_JNI_JniMult(JNIEnv *, jobject,
jint, jint);

/*
* Class: JNI_JNI
* Method: JniDiv
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_JNI_JNI_JniDiv(JNIEnv *, jobject,
jdouble, jdouble);
/*
* Class: JNI_JNI
* Method: JniPow
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_JNI_JNI_JniPow(JNIEnv *, jobject, jint,
jint);
/*
* Class: JNI_JNI
* Method: JniSqrt
* Signature: (I)V
*/
JNIEXPORT void JNICALL
Java_JNI_JNI_JniSqrt(JNIEnv *, jobject,
jint);
/*
* Class: JNI_JNI
* Method: JniMod
* Signature: (II)V
*/
JNIEXPORT void JNICALL
Java_JNI_JNI_JniMod(JNIEnv *, jobject, jint,
jint);

#ifdef cplusplus
}
#e
ndi
f
#e
ndi
f

C file_JNI.c

#include
<JNI.h>
#include<math
.h>
#define PI 3.14159265
JNIEXPORT void JNICALL
Java_JNI_JNI_JniAdd(JNIEnv *e, jobject
obj, jint no1, jint no2)
{
int add=no1+no2;
printf("Addition of nos.= %d",add);
}
JNIEXPORT void JNICALL
Java_JNI_JNI_JniSub(JNIEnv *e, jobject obj,
jint no1, jint no2)
{
int sub=no1-no2;
printf("\nSubtraction of nos. is= %d",sub);
}
JNIEXPORT void JNICALL
Java_JNI_JNI_JniMult(JNIEnv *e, jobject
obj, jint no1, jint no2)
{
int mult=no1*no2;
printf("\nMultiplication of nos. is= %d",mult);
}
JNIEXPORT void JNICALL
Java_JNI_JNI_JniDiv (JNIEnv *e, jobject
obj, jdouble no1, jdouble no2)
{
double div=no1/no2;
printf("\nDivision of nos. is= %.3f",div);
}
JNIEXPORT void JNICALL
Java_JNI_JNI_JniMod(JNIEnv *e, jobject
obj, jint no1, jint no2)
{
printf("\nRemainder is= %.3f",fmod(no1,no2));
}
JNIEXPORT void JNICALL
Java_JNI_JNI_JniPow(JNIEnv *e, jobject obj,
jint no1, jint no2)
{
printf("\nPower is= %.3f",pow(no1,no2));
}
JNIEXPORT void JNICALL
Java_JNI_JNI_JniSqrt(JNIEnv *e, jobject obj,
jint no1)
{
printf("\nSquare root %d is= %.3f",no1,sqrt(no1));
}

Output:

Microsoft Windows [Version 10.0.22621.674]


(c) Microsoft Corporation. All rights reserved.

C:\Users\Desktop\Practical\LP1\DLL>javac -h . JNI.java
C:\Users\Desktop\Practical\LP1\DLL> gcc -o libJNI.dll -shared -fPIC -
I"C:\Program Files\Java\jdk-18.0.1.1\include" -I"C:\Program Files\Java\jdk-
18.0.1.1\include\win32"

JNI using C
Enter first number: 21
Enter second number:
15
Addition of nos.= 36
Subtraction of nos. is=
6
Multiplication of nos. is=
315
Division of nos. is= 1.400
Power is= 68122318582951682000.000
Square root 15 is= 3.873
Remainder is= 6.000
Experiment 4

Problem Statement:
Write a program to solve Classical problems of Synchronization using Mutex and Semaphore.
Code:
package Tools;
import java.util.LinkedList;
public class ThreadExample{
public static void main(String args[])
throws InterruptedException
{
final PC pc=new PC();
Thread t1=new Thread(new Runnable() {
@Override
public void run()
{
try {
pc.produce();
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t2=new Thread(new Runnable()
{
@Override
public void run()
{
try {
pc.consume();
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
}
public static class PC{
LinkedList<Integer>list=new LinkedList<>();
int capacity=2;
public void produce() throws InterruptedException
{
int value=0;
while(true) {
synchronized(this)
{
while(list.size()==capacity)
wait();
System.out.println("Producer produced-
"+value);
list.add(value++);
notify();
Thread.sleep(1000);
}
}
}
public void consume()throws InterruptedException
{
while(true) {
synchronized(this)
{
while(list.size()==0)
wait();
int val=list.removeFirst();
System.out.println("Consumer consumed-
"+val);
notify();
Thread.sleep(1000);
}
}
}
}
}

Output:
Producer produced- 0
Producer produced- 1
Consumer consumed- 0
Consumer consumed- 1
Experiment 5

Problem Statement:
Write a program to simulate CPU scheduling algorithms: FCFS, SJF (Preemptive), Priority
(Non Preemptive) and Round Robin (Preemptive).

• FCFS
Code:
import java.util.*;
public class FCFS {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
int n;
float avgtat=0,avgwt=0;
System.out.println("*** First Come First Serve Scheduling ***");
System.out.print("Enter Number of Process: ");
n=sc.nextInt();
String process[]=new String[n];
int arrivaltime[]=new int[n];
int burstTime[]=new int[n];
int TAT[]=new int[n];
int waitingTime[]=new int[n];
int completionTime[]=new int[n];
for(int i=0;i<n;i++){
process[i]="P"+(i+1);
System.out.print("Enter Arrival Time for processor " + (i+1) + ":");
arrivaltime[i] = sc.nextInt();
System.out.print("Enter Burst Time for processor " + (i+1) + ": ");
burstTime[i] = sc.nextInt();
}

completionTime[0]=burstTime[0];
for(int i=0;i<n-1;i++){
completionTime[i+1]=completionTime[i]+burstTime[i+1];
}

System.out.println("*** First Come First Serve Scheduling ***");


System.out.println("Processor\tArrival time\tBrust time\tCompletion Time\t\tTurn
around time\tWaiting time");
System.out.println("
");
for(int i=0;i<n;i++){
TAT[i]=completionTime[i]-arrivaltime[i];
waitingTime[i]=TAT[i]-burstTime[i];
avgtat+=TAT[i];
avgwt+=waitingTime[i];
System.out.println(process[i]+"\t\t"+arrivaltime[i]+"ms\t\t"+burstTime[i]+"ms\t\t"+completio
nTime[i]+"ms\t\t\t"+TAT[i]+"ms\t\t\t"+waitingTime[i]+"ms");
}
System.out.println("Average turn around time of processor:
"+(avgtat/n)+"ms\nAverage waiting time of processor: "+(avgwt/n)+"ms");
}
}

Output:
*** First Come First Serve Scheduling ***
Enter Number of Process: 3
Enter Arrival Time for processor 1:0
Enter Burst Time for processor 1: 24
Enter Arrival Time for processor 2:0
Enter Burst Time for processor 2: 3
Enter Arrival Time for processor 3:0
Enter Burst Time for processor 3: 4

*** First Come First Serve Scheduling ***


Processor Arrival time Brust time Completion Time Turn around time Waiting time

P1 0ms 24ms 24ms 24ms 0ms


P2 0ms 3ms 27ms 27ms 24ms
P3 0ms 4ms 31ms 31ms 27ms
Average turn around time of processor: 27.333334ms
Average waiting time of processor: 17.0ms
• SJF – Shortest Job First (Preemptive)
Code:
CODE:-

import java.util.*;
public class SJF
{
public static void main (String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("*** Shortest Job First Scheduling (Preemptive) ***");
System.out.print("Enter no of process:");
int n= sc.nextInt();
String process[] = new String[n]; // it takes pid of process
int arrivaltime[] = new int[n]; // at means arrival time
int burstTime[] = new int[n]; // bt means burst time
int completionTime[] = new int[n]; // ct means complete time
int TAT[] = new int[n];// ta means turn around time
int waitingTime[] = new int[n]; // wt means waiting time
int flag[] = new int[n]; // f means it is flag it checks process is completed or not
int remburstTime[]= new int[n]; // it is also stores brust time
int st=0, tot=0;
float avgwt=0, avgta=0;
for (int i=0;i<n;i++)
{
process[i]="P"+(i+1);
System.out.print("Enter Arrival Time for processor " + (i+1) + ":");
arrivaltime[i]= sc.nextInt();
System.out.print("Enter Burst Time for processor " + (i+1) + ": ");
burstTime[i]= sc.nextInt();
remburstTime[i]= burstTime[i];
flag[i]= 0;}
while(true){
int min=99,c=n;
if (tot==n){
break;}
for(int i=0;i<n;i++)
{
if ((arrivaltime[i]<=st) && (flag[i]==0) && (burstTime[i]<min))
{
min=burstTime[i];
c=i;} }
if (c==n){
st++;
}
else{
burstTime[c]--;
st++;
if (burstTime[c]==0)
{
completionTime[c]= st;
flag[c]=1;
tot++;} }}
for(int i=0;i<n;i++)
{
TAT[i] = completionTime[i] - arrivaltime[i];
waitingTime[i] = TAT[i] - remburstTime[i];
avgwt+= waitingTime[i];
avgta+= TAT[i];
}
System.out.println("*** Shortest Job First Scheduling (Preemptive) ***");
System.out.println("Processor\tArrival time\tBrust time\tCompletion Time\t\tTurn around
time\tWaiting time");
System.out.println("
");
for(int i=0;i<n;i++)
{
System.out.println(process[i]+"\t\t"+arrivaltime[i]+"ms\t\t"+remburstTime[i]+"ms\t\t"+compl
etionTime[i]+"ms\t\t\t"+TAT[i]+"ms\t\t\t"+waitingTime[i]+"ms");
}
System.out.println("\nAverage turn around time is "+ (float)(avgta/n));
System.out.println("Average waiting time is "+ (float)(avgwt/n));
sc.close();}}

Output:
*** Shortest Job First Scheduling (Preemptive) ***
Enter no of process:5
Enter Arrival Time for processor 1:2
Enter Burst Time for processor 1: 6
Enter Arrival Time for processor 2:5
Enter Burst Time for processor 2: 2
Enter Arrival Time for processor 3:1
Enter Burst Time for processor 3: 8
Enter Arrival Time for processor 4:0
Enter Burst Time for processor 4: 3
Enter Arrival Time for processor 5:4
Enter Burst Time for processor 5: 4
*** Shortest Job First Scheduling (Preemptive) ***
Processor Arrival time Brust time Completion Time Turn around time
Waiting time
P4 0ms 3ms 3ms 3ms
0ms
P3 1ms 8ms 23ms 22ms
14ms
P1 2ms 6ms 15ms 13ms
7ms
P5 4ms 4ms 10ms 6ms
2ms
P2 5ms 2ms 7ms 2ms
0ms

Average turn around time is 9.2


Average waiting time is 4.6
• Priority (Non-preemptive)
Code:
import java.util.*;
class PriorityScheduling {
public static void main(String[] args) {
System.out.println("*** Priority Scheduling (Preemptive) ***");
System.out.print("Enter Number of Process: ");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String process[] = new String[n];
int arrivaltime[] = new int[n];
int burstTime[] = new int[n];
int completionTime[] = new int[n];
int priority[] = new int[n+1];
int TAT[] = new int[n];
int waitingTime[] = new int[n];
int burstTimecopy[]=new int[n];
int min=0,count=0;
int time = 0,end;
double avgWT=0,avgTAT=0;
for (int i = 0; i < n; i++) {
process[i] = "P" + (i+1);
System.out.println("");
System.out.print("Enter Arrival Time for processor " + (i+1) + ":");
arrivaltime[i] = sc.nextInt();
System.out.print("Enter Burst Time for processor " + (i+1) + " : ");
burstTime[i] = sc.nextInt();
System.out.print("Enter Priority for " + (i+1) + " process: ");
priority[i] = sc.nextInt();
}
System.arraycopy(burstTime, 0, burstTimecopy, 0, n);
priority[n]=999;
for(time =0;count!=n;time++){
min=n;
for(int i=0;i<n;i++){
if(arrivaltime[i]<=time && priority[i]<priority[min] && burstTime[i]>0)
min=i;
}
burstTime[min]--;
if(burstTime[min]==0){
count++;
end=time+1;
completionTime[min]=end;
waitingTime[min]=end -arrivaltime[min]-burstTimecopy[min];
TAT[min]=end-arrivaltime[min];
}
}

for(int i=0;i<n;i++)
{
avgTAT += TAT[i];
avgWT += waitingTime[i];
}
System.out.println("\n*** Priority Scheduling (Preemptive) ***");
System.out.println("Processor\tArrival time\tBrust time\tCompletion Time\t\tTurn around
time\tWaiting time");
System.out.println("
");
for (int i = 0; i < n; i++) {
System.out.println(process[i]+"\t\t"+arrivaltime[i]+"ms\t\t"+burstTimecopy[i]+"ms\t\t"+com
pletionTime[i]+"ms\t\t\t"+TAT[i]+"ms\t\t\t"+waitingTime[i]+"ms");
}
avgWT/= n;
avgTAT/= n;
System.out.println("\nAverage Wating Time: " + avgWT);
System.out.println("Average Turn Around Time: " + avgTAT);
}
}

Output:
*** Priority Scheduling (Preemptive) ***
Enter Number of Process: 7
Enter Arrival Time for processor 1:0
Enter Burst Time for processor 1 : 1
Enter Priority for 1 process: 2
Enter Arrival Time for processor 2:1
Enter Burst Time for processor 2 : 7
Enter Priority for 2 process: 6
Enter Arrival Time for processor 3:2
Enter Burst Time for processor 3 : 3
Enter Priority for 3 process: 3
Enter Arrival Time for processor 4:3
Enter Burst Time for processor 4 : 6
Enter Priority for 4 process: 5
Enter Arrival Time for processor 5:4
Enter Burst Time for processor 5 : 5
Enter Priority for 5 process: 4
Enter Arrival Time for processor 6:5
Enter Burst Time for processor 6 : 15
Enter Priority for 6 process: 10
Enter Arrival Time for processor 7:15
Enter Burst Time for processor 7 : 8
Enter Priority for 7 process: 9
*** Priority Scheduling (Preemptive) ***
Processor Arrival time Brust time Completion Time Turn around time Waiting time

P1 0ms 1ms 1ms 1ms


0ms
P2 1ms 7ms 22ms 21ms
14ms
P3 2ms 3ms 5ms 3ms
0ms
P4 3ms 6ms 16ms 13ms 7ms
P5 4ms 5ms 10ms 6ms 1ms
P6 5ms 15ms 45ms 40ms
25ms
P7 15ms 8ms 30ms 15ms 7ms

Average Wating Time: 7.714285714285714


Average Turn Around Time: 14.142857142857142
• Round Robin (Preemptive)
Code:
import java.util.*;
class Process {
int processID;
int arrival, burst, waiting, turnAround, remainingTime;
int finish,completionTime;
}
public class RRScheduling {
public static void main(String[] args) {
int n,sumBurst=0,quantum,time;
double avgWAT=0,avgTAT=0;
Scanner sc=new Scanner(System.in);
Queue<Integer> q = new LinkedList<>();
System.out.println("*** RR Scheduling (Preemptive) ***");
System.out.print("Enter Number of Process: ");
n=sc.nextInt();
Process[] p = new Process[n];
for (int i = 0; i < n; i++) {
p[i] = new Process();
p[i].processID = i + 1;
System.out.print("Enter the arrival time for P" + (i + 1) + ": ");
p[i].arrival = sc.nextInt();
System.out.print("Enter the burst time for P" + (i + 1) + ": ");
p[i].burst = sc.nextInt();
p[i].remainingTime = p[i].burst;
p[i].finish = 0;
sumBurst += p[i].burst;
System.out.println();
}
System.out.print("\nEnter time quantum: ");
quantum = sc.nextInt();
Process pTemp;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (p[i].arrival > p[j].arrival) {
pTemp = p[i];
p[i] = p[j];
p[j] = pTemp;
}
}
}
q.add(0);
for (time = p[0].arrival; time < sumBurst;) {
Integer I = q.remove();
int i = I.intValue();
if (p[i].remainingTime <= quantum) {
time += p[i].remainingTime;
p[i].remainingTime = 0;
p[i].finish = 1;
p[i].completionTime=time;
p[i].waiting = time - p[i].arrival - p[i].burst;
p[i].turnAround = time - p[i].arrival;
for (int j = 0; j < n; j++) {
Integer J = Integer.valueOf(j);
if ((p[j].arrival <= time) && (p[j].finish != 1) && (!q.contains(J)))
q.add(j);
}
} else {
time += quantum;
p[i].remainingTime -= quantum;
for (int j = 0; j < n; j++) {
Integer J = Integer.valueOf(j);
if (p[j].arrival <= time && p[j].finish != 1 && i != j && (!q.contains(J)))
q.add(j);
}
q.add(i);
}
}
System.out.println("\n*** RR Scheduling (Preemptive) ***");
System.out.println("Processor\tArrival time\tBrust time\tCompletion Time\t\tTurn
around time\tWaiting time");
System.out.println("
");
for (int i = 0; i < n; i++) {

System.out.println(("P"+(i+1))+"\t\t"+p[i].arrival+"ms\t\t"+p[i].burst+"ms\t\t"+p[i].completio
nTime+"ms\t\t\t"+p[i].turnAround+"ms\t\t\t"+p[i].waiting+"ms");
avgWAT += p[i].waiting;
avgTAT += p[i].turnAround;
}
System.out.println("\nAverage turn around time of processor:
"+(avgTAT/n)+"ms\nAverage waiting time of processor: "+(avgWAT/n)+"ms");
}
}
Output:
*** RR Scheduling (Preemptive) ***
Enter Number of Process: 6
Enter the arrival time for P1: 0
Enter the burst time for P1: 7
Enter the arrival time for P2: 1
Enter the burst time for P2: 4
Enter the arrival time for P3: 2
Enter the burst time for P3: 15
Enter the arrival time for P4: 3
Enter the burst time for P4: 11
Enter the arrival time for P5: 4
Enter the burst time for P5: 20
Enter the arrival time for P6: 4
Enter the burst time for P6: 9
Enter time quantum: 5

*** RR Scheduling (Preemptive) ***


Processor Arrival time Brust time Completion Time Turn around time Waiting time

P1 0ms 7ms 31ms 31ms 24ms


P2 1ms 4ms 9ms 8ms 4ms
P3 2ms 15ms 55ms 53ms 38ms
P4 3ms 11ms 56ms 53ms 42ms
P5 4ms 20ms 66ms 62ms 42ms
P6 4ms 9ms 50ms 46ms 37ms
Average turn around time of processor: 42.166666666666664ms
Average waiting time of processor: 31.166666666666668ms
Experiment 6

Problem Statement:
Write a program to simulate memory placement strategies.
1. First fit
2. Best fit
3. Worst fit
4. Next fit

• First fit
Code:
import java.util.Scanner;
public class FirstFit {
static void firstFit(int blockSize[], int m,int processSize[], int n,int
remblockSize[])
{
int allocation[] = new int[n];
for (int i = 0; i < allocation.length; i++) {
allocation[i] = -1;
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (blockSize[j] >= processSize[i])
{
allocation[i] = j;
blockSize[j] -= processSize[i];
remblockSize[i]=blockSize[j];
break;
}}}
System.out.println("\nProcess No.\tProcess Size\tBlock no.\tRemaninig Block
Size");
for (int i = 0; i < n; i++)
{
System.out.print(" " + (i+1) + "\t\t" +processSize[i] + "\t\t");
if (allocation[i] != -1) {
System.out.print((allocation[i] +
1)+"\t\t"+remblockSize[i]);
}
else {
System.out.print("Not
Allocated"+"\t"+remblockSize[i]);
}
System.out.println();
}}
public static void main(String[] args) {
int m,n,num;
Scanner in=new Scanner(System.in);
System.out.print("Enter how many number of blocks you want to enter:");
m=in.nextInt();
int blockSize[]=new int[m];
int remblockSize[]=new int[m];
for(int i=0;i<m;i++) {
System.out.print("Enter Data "+(i+1)+":");
num=in.nextInt();
blockSize[i]=num;
}
System.out.print("Enter how many number of process you want to enter:");
n=in.nextInt();
int processSize[]=new int[n];
for(int i=0;i<n;i++) {
System.out.print("Enter Data "+(i+1)+":");
num=in.nextInt();
processSize[i]=num;
}
firstFit(blockSize, m, processSize, n,remblockSize);
}}

Output:
Enter how many number of blocks you want to enter:4
Enter Data 1:10
Enter Data 2:15
Enter Data 3:15
Enter Data 4:15
Enter how many number of process you want to enter:4
Enter Data 1:10
Enter Data 2:15
Enter Data 3:14
Enter Data 4:16
Process No. Process Size Block no. Remaninig Block Size
1 10 1 0
2 15 2 0
3 14 3 1
4 16 Not Allocated 0
• Best fit
Code:
import java.util.Scanner;
public class BestFit {
static void bestFit(int blockSize[], int m, int processSize[],int n,int
remblockSize[])
{
int allocation[] = new int[n];
for (int i = 0; i < allocation.length; i++) {
allocation[i] = -1; }
for (int i=0; i<n; i++)
{
int bestIdx = -1;
for (int j=0; j<m; j++)
{
if (blockSize[j] >= processSize[i])
{
if (bestIdx == -1)
bestIdx = j;
else if (blockSize[bestIdx] > blockSize[j])
bestIdx = j;
}}
if (bestIdx != -1)
{
allocation[i] = bestIdx;
blockSize[bestIdx] -= processSize[i];
remblockSize[i]=blockSize[bestIdx];
}}
System.out.println("\nProcess No.\tProcess Size\tBlock no.\tRemaninig Block Size");
for (int i = 0; i < n; i++)
{
System.out.print(" " + (i+1) + "\t\t" + processSize[i] + "\t\t");
if (allocation[i] != -1) {
System.out.print((allocation[i] +
1)+"\t\t"+remblockSize[i]); }
else {
System.out.print("Not
Allocated"+"\t"+remblockSize[i]); }
System.out.println();}}
public static void main(String[] args) {
int m,n,num;
Scanner in=new Scanner(System.in);
System.out.print("Enter how many number of blocks you want to enter:");
m=in.nextInt();
int remblockSize[]=new int[m];
int blockSize[]=new int[m];
for(int i=0;i<m;i++) {
System.out.print("Enter Data "+(i+1)+":");
num=in.nextInt();
blockSize[i]=num;
}
System.out.print("Enter how many number of process you want to enter:");
n=in.nextInt();
int processSize[]=new int[n];
for(int i=0;i<n;i++) {
System.out.print("Enter Data "+(i+1)+":");
num=in.nextInt();
processSize[i]=num;
}
bestFit(blockSize, m, processSize, n,remblockSize); }}

Output:
Enter how many number of blocks you want to enter:4
Enter Data 1:10
Enter Data 2:15
Enter Data 3:15
Enter Data 4:15
Enter how many number of process you want to enter:4
Enter Data 1:10
Enter Data 2:15
Enter Data 3:14
Enter Data 4:16
Process No. Process Size Block no. Remaninig Block Size
1 10 1 0
2 15 2 0
3 14 3 1
4 16 Not Allocated 0
• Worst fit
Code:
import java.util.Scanner;
public class WorstFit {
static void worstFit(int blockSize[], int m, int processSize[],int n,int remblockSize[])
{
int allocation[] = new int[n];
for (int i = 0; i < allocation.length; i++) {
allocation[i] = -1;}
for (int i=0; i<n; i++)
{
int wstIdx = -1;
for (int j=0; j<m; j++)
{
if (blockSize[j] >= processSize[i])
{
if (wstIdx == -1)
wstIdx = j;
else if (blockSize[wstIdx] < blockSize[j])
wstIdx = j;
}}
if (wstIdx != -1)
{
allocation[i] = wstIdx;
blockSize[wstIdx] -= processSize[i];
remblockSize[i]=blockSize[wstIdx];
}}
System.out.println("\nProcess No.\tProcess Size\tBlock no.\tRemaninig Block Size");
for (int i = 0; i < n; i++)
{
System.out.print(" " + (i+1) + "\t\t" + processSize[i] + "\t\t");
if (allocation[i] != -1)
System.out.print((allocation[i] +
1)+"\t\t"+remblockSize[i]);
else
System.out.print("Not
Allocated"+"\t"+remblockSize[i]);
System.out.println();
}}
public static void main(String[] args) {
int m,n,num;
Scanner in=new Scanner(System.in);
System.out.print("Enter how many number of blocks you want to enter:");
m=in.nextInt();
int remblockSize[]=new int[m];
int blockSize[]=new int[m];
for(int i=0;i<m;i++) {
System.out.print("Enter Data "+(i+1)+":");
num=in.nextInt();
blockSize[i]=num;
}
System.out.print("Enter how many number of process you want to enter:");
n=in.nextInt();
int processSize[]=new int[n];
for(int i=0;i<n;i++) {
System.out.print("Enter Data "+(i+1)+":");
num=in.nextInt();
processSize[i]=num;
}
worstFit(blockSize, m, processSize, n,remblockSize);
}}

Output:
Enter how many number of blocks you want to enter:4
Enter Data 1:10
Enter Data 2:15
Enter Data 3:15
Enter Data 4:15
Enter how many number of process you want to enter:4
Enter Data 1:10
Enter Data 2:15
Enter Data 3:14
Enter Data 4:16
Process No. Process Size Block no. Remaninig Block Size
1 10 2 5
2 14 3 1
3 15 4 0
4 16 Not Allocated 0
• Next fit
Code:
import java.util.Arrays;
import java.util.Scanner;
public class NextFit {
static void NextFit(int blockSize[], int m, int processSize[], int n,int remblockSize[]) {
int allocation[] = new int[n], j = 0;
Arrays.fill(allocation, -1);
for (int i = 0; i < n; i++) {
int count=0;
while (count<m){
count++;
if (blockSize[j] >= processSize[i]) {
allocation[i] = j;
blockSize[j] -= processSize[i];
remblockSize[i]=blockSize[j];
break;
}
j=(j + 1) % m;
count+=1;
}}
System.out.println("\nProcess No.\tProcess Size\tBlock no.\tRemaninig Block Size");
for (int i = 0; i < n; i++) {
System.out.print( i + 1 + "\t\t" + processSize[i]+ "\t\t");
if (allocation[i] != -1) {
System.out.print((allocation[i] +
1)+"\t\t"+remblockSize[i]);
} else {
System.out.print("Not
Allocated"+"\t"+remblockSize[i]);
}
System.out.println("");
}}
public static void main(String[] args) {
int m,n,num;
Scanner in=new Scanner(System.in);
System.out.print("Enter how many number of blocks you want to enter:");
m=in.nextInt();
int blockSize[]=new int[m];
int remblockSize[]=new int[m];
for(int i=0;i<m;i++) {
System.out.print("Enter Data "+(i+1)+":");
num=in.nextInt();
blockSize[i]=num;
}
System.out.print("Enter how many number of process you want to enter:");
n=in.nextInt();
int processSize[]=new int[n];
for(int i=0;i<n;i++) {
System.out.print("Enter Data "+(i+1)+":");
num=in.nextInt();
processSize[i]=num;
}
NextFit(blockSize, m, processSize, n,remblockSize);
}
}

Output:
Enter how many number of blocks you want to enter:4
Enter Data 1:10
Enter Data 2:15
Enter Data 3:15
Enter Data 4:15
Enter how many number of process you want to enter:4
Enter Data 1:10
Enter Data 2:15
Enter Data 3:14
Enter Data 4:16
Process No. Process Size Block no. Remaninig Block Size
1 10 1 0
2 15 2 0
3 14 3 1
4 16 Not Allocated 0
Experiment 7

Problem Statement:
Write a program to simulate page replacement algorithm.
• First in First Out
Code:
import java.util.*;
public class FIFO {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int noofpages,capacity,index=0;
int hit=0,fault=0;
double faultRatio,hitRatio;
System.out.print("Enter the number of pages you want to enter: ");
noofpages=sc.nextInt();
int pages[]=new int[noofpages];
for (int i=0;i<noofpages;i++) {
pages[i]=sc.nextInt();
}
System.out.print("Enter the capacity of frame: ");
capacity=sc.nextInt();
int frame[]=new int[capacity];
int table[][]=new int[noofpages][capacity];

for(int i=0;i<capacity;i++){
frame[i]=-1;
}
System.out.println("\n
");
for(int i=0;i<noofpages;i++){
int search=-1;
for(int j = 0; j < capacity; j++)
{
if(frame[j] == pages[i])
{
search = j;
hit++;
System.out.printf("%4s","H");
break;
}}
if(search == -1)
{
frame[index] = pages[i];
fault++;
System.out.printf("%4s","F");
index++;
if(index == capacity){
index = 0;
}}
System.arraycopy(frame, 0, table[i], 0, capacity);
}
System.out.println("\n
");
for (int i = 0; i < capacity; i++) {
for (int j = 0; j < noofpages; j++)
System.out.printf("%3d ", table[j][i]);
System.out.println();
}
System.out.println("
");
faultRatio=((double)fault/noofpages)*100;
hitRatio=((double)hit/noofpages)*100;
System.out.println("Page Fault: "+fault+"\nPage Hit: "+hit);
System.out.printf("Hit Ratio:%.2f \nFault Ratio:%.2f
",hitRatio,faultRatio);
}}

Output:
Enter the number of pages you want to enter: 13
7012030423032
Enter the capacity of frame: 4

F F F F H F H F H H F H H

7 7 7 7 7 3 3 3 3 3 3 3 3
-1 0 0 0 0 0 0 4 4 4 4 4 4
-1 -1 1 1 1 1 1 1 1 1 0 0 0
-1 -1 -1 2 2 2 2 2 2 2 2 2 2

Page Fault: 7
Page Hit: 6
Hit Ratio:46.15
Fault Ratio:53.85
• Optimal Page Replacement
Code:
import java.util.Scanner;

public class OptimalPageReplacement {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int noofpages, capacity, ptr = 0, hit = 0, fault = 0;
boolean isFull=false;
double hitRatio,faultRatio;
System.out.print("Enter the number of pages you want to enter: ");
noofpages = sc.nextInt();
int pages[] = new int[noofpages];
for (int i = 0; i < noofpages; i++) {
pages[i] = sc.nextInt();
}
System.out.print("Enter the capacity of frame: ");
capacity = sc.nextInt();
int frame[] = new int[capacity];
int table[][] = new int[noofpages][capacity];
for (int i = 0; i < capacity; i++) {
frame[i] = -1;
}
System.out.println(" ");
for (int i = 0; i < noofpages; i++) {
int search = -1;
for (int j = 0; j < capacity; j++) {
if (frame[j] == pages[i]) {
search = j;
hit++;
System.out.printf("%4s","H");
break;
}}
if (search == -1) {
if (isFull) {
int[] index = new int[capacity];
boolean[] index_flag = new boolean[capacity];
for (int j = i + 1; j < noofpages; j++) {
for (int k = 0; k < capacity; k++) {
if ((pages[j] == frame[k]) &&
(!index_flag[k])) {
index[k] = j;
index_flag[k] = true;
break;
}} }
int max = index[0];
ptr = 0;
if (max == 0)
max = 200;
for (int j = 0; j < capacity; j++) {
if (index[j] == 0)
index[j] = 200;
if (index[j] > max) {
max = index[j];
ptr = j;
} } }
frame[ptr] = pages[i];
fault++;
System.out.printf("%4s","F");
if (!isFull) {
ptr++;
if (ptr == capacity) {
ptr = 0;
isFull = true;
}} }
System.arraycopy(frame, 0, table[i], 0, capacity);
}
System.out.println("\n ");
for (int i = 0; i < capacity; i++) {
for (int j = 0; j < noofpages; j++)
System.out.printf("%3d ", table[j][i]);
System.out.println();
}
System.out.println(" ");
hitRatio = ((double)hit / noofpages) * 100;
faultRatio = ((double)fault / noofpages) * 100;
System.out.println("Page Fault: " + fault + "\nPage Hit: " + hit);
System.out.printf("Hit Ratio:%.2f \nFault Ratio:%.2f ", hitRatio, faultRatio);
}}
Output:
Enter the number of pages you want to enter: 13
7012030423032
Enter the capacity of frame: 4

F F F F H F H F H H H H H

7 7 7 7 7 3 3 3 3 3 3 3 3
-1 0 0 0 0 0 0 0 0 0 0 0 0
-1 -1 1 1 1 1 1 4 4 4 4 4 4
-1 -1 -1 2 2 2 2 2 2 2 2 2 2

Page Fault: 6 || Page Hit: 7 || Hit Ratio:53.85 || Fault Ratio:46.


• Least Recently Used
Code:
import java.util.*;
public class LeastRecentlyUsed {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Integer> arr = new ArrayList<>();
int noofpages, capacity, hit = 0, fault = 0, index = 0;
boolean isFull = false;
double hitRatio, faultRatio;
System.out.print("Enter the number of pages you want to enter: ");
noofpages = sc.nextInt();
int pages[] = new int[noofpages];
for (int i = 0; i < noofpages; i++) {
pages[i] = sc.nextInt();
}
System.out.print("Enter the capacity of frame: ");
capacity = sc.nextInt();
int frame[] = new int[capacity];
int table[][] = new int[noofpages][capacity];
for (int i = 0; i < capacity; i++) {
frame[i] = -1;
}
System.out.println("
");
for (int i = 0; i < noofpages; i++) {
if (arr.contains(pages[i])) {
arr.remove((Integer) pages[i]);
}
arr.add(pages[i]);
int search = -1;
for (int j = 0; j < capacity; j++) {
if (frame[j] == pages[i]) {
search = j;
hit++;
System.out.printf("%4s","H");
break;
}
}
if (search == -1) {
if (isFull) {
int min_loc = noofpages;
for (int j = 0; j < capacity; j++) {
if (arr.contains(frame[j])) {
int temp = arr.indexOf(frame[j]);
if (temp < min_loc) {
min_loc = temp;
index = j;
}}}}
frame[index] = pages[i];
fault++;
System.out.printf("%4s","F");
index++;
if (index == capacity) {
index = 0;
isFull = true;
}}
System.arraycopy(frame, 0, table[i], 0, capacity);
}
System.out.println("\n
--");
for (int i = 0; i < capacity; i++) {
for (int j = 0; j < noofpages; j++)
System.out.printf("%3d ", table[j][i]);
System.out.println();
}
System.out.println("
");
hitRatio = ((double)hit / noofpages) * 100;
faultRatio = ((double)fault / noofpages) * 100;
System.out.println("Page Fault: " + fault + "\nPage Hit: " + hit);
System.out.printf("Hit Ratio:%.2f \nFault Ratio:%.2f ", hitRatio, faultRatio);

}}

Output:
Enter the number of pages you want to enter: 13
7012030423032
Enter the capacity of frame: 4

F F F F H F H F H H H H H

7 7 7 7 7 3 3 3 3 3 3 3 3
-1 0 0 0 0 0 0 0 0 0 0 0 0
-1 -1 1 1 1 1 1 4 4 4 4 4 4
-1 -1 -1 2 2 2 2 2 2 2 2 2 2

Page Fault: 6
Page Hit: 7
Hit Ratio:53.85
Fault Ratio:46.15

You might also like