0% found this document useful (0 votes)
38 views137 pages

AREGS Website Design & Development Guide

free

Uploaded by

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

AREGS Website Design & Development Guide

free

Uploaded by

Adinath Sonawane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

lOMoARcPSD|58943265

TE-LP-I Lab Manual 2023-24

Computer Engineering (Sinhgad Technical Education Society)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Adinath Sonawane (adinaths109@[Link])
lOMoARcPSD|58943265

PAGE \* MERGEFORMAT 1

SINHGAD TECHNICAL EDUCATION SOCIETY’S

SINHGAD INSTITUTE OF TECHNOLOGY


Kusgaon (Bk), Lonavala 410401

DEPARTMENT OF COMPUTER ENGINEERING

LAB MANUAL
Academic year 2023-24

T.E. COMPUTER (SEM – I)


Laboratory Practice-I (310248)

TEACHING SCHEME EXAMINATION SCHEME


PRACTICAL: 4 HRS/WEEK TERM WORK: 25 MARKS
PRACTICAL EXAM: 25 MARKS

PAGE \* MERGEFORMAT 1

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

PAGE \* MERGEFORMAT 1

Vision and Mission of Institute

VISION

We are commi琀琀ed to produce not only good engineers but good human beings, also.

MISSION

Holistic development of students and teachers is that we believe in and work for, We
strive to achieve this by imbibing a unique value system, transparent work culture,
excellent academic and physical environment conducive to learning, creativity and
technology transfer. Our mandate is to generate, preserve and share knowledge for
developing a vibrant society.

Vision and Mission of Department

VISION

We strive to produce globally competent computer professionals enriched with


innovative skills and good moral values with societal concerns.

MISSION
M1: To provide broad-based education and contemporary knowledge by
adopting modern teaching-learning methods.
M2: To inculcate a spirit of innovation in students through industrial
interactions.
M3: To develop individual’s potential to its fullest extent so that they can
emerge as gifted leaders in their fields

PAGE \* MERGEFORMAT 1

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

PAGE \* MERGEFORMAT 1

Short Term Goals


 To increase the count of university rankers
 To maintain 90% and above results with maximum no. of distinctions.

 To inculcate professional behavior in students through seminars, mock interviews, etc.

 To develop research oriented work culture among faculty and students.

 To initiate relevant value-addition programs and certifications for improving


employability.

 Build strong alliances that bring the know-how of the business community to complete
the training of students through projects.

 To encourage faculty by creating opportunities of higher education.

Long Term Goals


 . To achieve 100% placements through Campus Interviews

 To create better entrepreneurs in the IT Sector


 To establish and strengthen Industry-Institute interaction and be industry solution
providers.
 To establish a state-of-the-art R&D institute for project-based research creating
opportunities for faculty to be a resource.

 To make the department self-reliant through revenue generation by taking up projects


from Industry
 To strive hard to meet the social, ecological, and ethical needs of the nation.

Program Educational Objectives (PEO’s)


1. To prepare globally competent graduates having strong fundamentals and domain
knowledge to provide effective solutions for engineering problems.

PAGE \* MERGEFORMAT 1

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

PAGE \* MERGEFORMAT 1

2. To prepare the graduates to work as a committed professional with strong professional


ethics and values, sense of responsibilities, understanding of legal, safety, health, societal,
cultural and environmental issues.
3. To prepare committed and motivated graduates with research attitude, lifelong learning,
investigative approach, and multidisciplinary thinking.
4. To prepare the graduates with strong managerial and communication skills to work
effectively as individual as well as in teams.

Program Outcomes: POs

Students are expected to know and be able –


PO1- Engineering Knowledge: - To apply knowledge of mathematics, science, engineering
fundamentals, problem solving skills, algorithmic analysis and mathematical modelling to the
solution of complex engineering problems.
PO2- Problem Analysis: - Identify, formulate, review research literature and analyze complex
engineering problems reaching substantiated conclusion using first principals of mathematics,
natural sciences and engineering sciences.
PO3- Design / Development of solutions: - Design solutions for complex engineering problems
and design system components or processes that meet the specified needs with appropriate
considerations for the public health and safety, and the cultural, social and environmental
considerations.
PO4- Conduct Investigations of Complex Problems: - Use research based knowledge and
research methods including design of experiments, analysis and interpretation of data, and
modeling to complex engineering activities with an understanding of the limitations.
PO5- Modern Tool Usage: - Create, select and apply appropriate techniques, resources and
modern engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.
PO6- the Engineer and Society: - Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
PO7- Environment and Sustainability:- Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.

PAGE \* MERGEFORMAT 1

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

PAGE \* MERGEFORMAT 1

PO8- Ethics:- Apply ethical principles and commit to professional ethics and responsibilities
and norms of engineering practice.
PO9- Individual and Team work :-Function effectively as an individual and as a member or
leader in diverse teams, and in multidisciplinary settings.
PO10- Communication Skill:- Communicate effectively on complex engineering activities with
the engineering community and with society at large, such as being able to comprehend and
write effective reports and design documentation, make effective presentations, and give and
receive dear instructions.
PO11- Project management Finance: - Demonstrate knowledge and understanding of
engineering and management principles and apply these to one’s own work as a member and
leader in a team to manage projects and in multidisciplinary environment.
PO12- Life-long Learning: - Recognize the need for, and have the preparations and ability to
engage in independent and lifelong learning in the broadest context of technological change.

Program Specific Outcomes: PSOs

A graduate of the Computer Engineering Program will demonstrate-


PSO1- Professional Skills-The ability to understand, analyze and develop computer programs in
the areas related to algorithms, system software, multimedia, web design, big data analytics, and
networking for efficient design of computer-based systems of varying.
PSO2- Problem-Solving Skills- The ability to apply standard practices and strategies in software
project development using open-ended programming environments to deliver a quality product
for business success.
PSO3- Successful Career and Entrepreneurship- The ability to employ modern computer
languages, environments, and platforms in creating innovative career paths to be an
entrepreneur, and a zest for higher studies.

PAGE \* MERGEFORMAT 1

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

PAGE \* MERGEFORMAT 1

Course Objectives:
1) To learn system programming tools
2) To learn modern operating system
3) To learn various techniques, tools, application in IOT and embedded
system. HCI/ DS/ SPM.

Course Outcomes:
On completion of the course, learners will be able to
Systems Programming and Operating System
CO1: Implement language translators
CO2: Use tools like LEX and YACC
CO3: Implement internals and functionalities of Operating System
 Internet of Things and Embedded Systems
CO4: Design IoT and Embedded Systems based application
CO5: Develop smart applications using IoT
CO6: Develop IoT applications based on cloud environment
OR
Human Computer Interface
CO4: Implement the interactive designs for feasible data search and retrieval
CO5: Analyze the scope of HCI in various paradigms like ubiquitous computing,
Virtual Reality and, multi-media, worldwide web related environments
CO6: Analyze and identify user models, user support, socio-organizational issues
and stakeholder requirements of HCI systems
OR
Distributed Systems
CO4: Demonstrate knowledge of the core concepts and techniques in Distributed
Systems

PAGE \* MERGEFORMAT 1

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

PAGE \* MERGEFORMAT 1

CO5: Apply the principles of state-of-the-Art Distributed Systems in real time


applications
CO6: Design, build and test application programs on Distributed Systems
OR
Software Project Management
CO4: Apply Software Project Management tools
CO5: Implement software project planning and scheduling
CO6: Analyze staffing in software project

PAGE \* MERGEFORMAT 1

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

PAGE \* MERGEFORMAT 1

SINHGAD INSTITUTE OF TECHNOLOGY

DEPARTMENT OF COMPUTER ENGINEERING

CERTIFICATE

This is to certify that, Mr. /Miss _________________________________ of class

TE Roll No.______Exam Seat No. ________________________

has completed all the practical work in the subject Laboratory Practices-I,

satisfactorily, as prescribed by Savitribai Phule Pune University, Pune (SPPU) in

the Academic Year 2023-24.

Subject In-charge Head of Department

Prof. V S Kadam Dr. S. D. Babar

Guidelines for Laboratory /Term Work Assessment

PAGE \* MERGEFORMAT 1

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

PAGE \* MERGEFORMAT 1

Continuous assessment of laboratory work is based on overall performance and


Laboratory assignments performance of student. Each Laboratory assignment assessment will
assign grade/marks based on parameters with appropriate weightage. Suggested parameters for
overall assessment as well as each Laboratory assignment assessment include- timely
completion, performance, innovation, efficient codes, punctuality and neatness

Guidelines for Laboratory Conduction

The instructor is expected to frame the assignments by understanding the prerequisites,


technological aspects, utility and recent trends related to the topic. The assignment framing
policy need to address the average students and inclusive of an element to attract and promote
the intelligent students. The instructor may set multiple sets of assignments and distribute
among batches of students. It is appreciated if the assignments are based on real world
problems/applications. Use of open source software is encouraged. In addition to these,
instructor may assign one real life application in the form of a mini-project based on the
concepts learned. Instructor may also set one assignment or mini-project that is suitable to
respective branch beyond the scope of syllabus.

Programming Tools:
Internet of things and embedded system: - Raspberry Pi / Arduino Programming;
Arduino IDE / Python.

Guidelines for Oral Examination

. During oral assessment, the expert evaluator should give the maximum weightage to
the satisfactory implementation of the problem statement. The supplementary and relevant
questions may be asked at the time of evaluation to test the student’s for advanced learning,
understanding of the fundamentals, effective and efficient implementation. So encouraging
efforts, transparent evaluation and fair approach of the evaluator will not create any uncertainty
or doubt in the minds of the students. So adhering to these principles will consummate our team
efforts to the promising start of the student's academics.

PAGE \* MERGEFORMAT 1

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

PAGE \* MERGEFORMAT 1

INDEX
Sr. Assignment Date of Date of Marks Sign of
no. performance Submission Obtained Faculty
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.

2 Design suitable data structures and


implement Pass-I and Pass-II of a two-
pass macro- processor.

3 Write a program to simulate CPU


Scheduling Algorithms: FCFS, SJF
(Preemptive), Priority (Non-Preemptive)
and Round Robin (Preemptive).

4 Write a program to simulate Memory


placement strategies – best fit, first fit,
next fit and worst fit.

Total
Marks

Total marks: - /60

Date: Subject Teacher Sign


Name of the Student: ______________________________________ Roll no: ___
CLASS: - T.E. [Computer Engineering] Division: B Course: - Lab Practices-I
Assignment-1
PAGE \* MERGEFORMAT 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.
Downloaded by Adinath Sonawane (adinaths109@[Link])
lOMoARcPSD|58943265

Marks: /10
Date of Performance: Sign with Date
T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I
/ / 2023

Data Structure for Two Pass Assembler Scheme


Data Structure of Assembler:
a) Operation code table (OPTAB) :This is used for storing mnemonic,
operation code and class of instruction
Structure of OPTAB is as follows
b) Data structure updated during translation: Also called as translation time data

structure. They are


I. SYMBOL TABLE (SYMTAB) : Ii contains entries such as symbol, it’s address and value.
II. LITERAL TABLE (LITTAB) : it contains entries such as literal and it's value.
III . POOL TABLE (POOLTAB): Contains literal number of the starting literal of each literal
pool.

Design of Two Pass Assembler Scheme


Tasks performed by the passes of two-pass assembler are as follows:

Pass I: -
Separate the symbol, mnemonic opcode and operand fields.
Determine the storage-required for every assembly language statement and update the
location counter.
Build the symbol table and the literal table.
Construct the intermediate code for every assembly language statement.

0 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Pass II: -
Synthesize the target code by processing the intermediate code generated during pass1
INTERMEDIATE CODE REPRESENTATION
The intermediate code consists of a set of IC units, each IC unit consisting of the
following three fields
1. Address
2. Representation of the mnemonic opcode
3. Representation of operands
Where statement class can be one of IS,DL and AD standing for imperative statement,
declaration statement and assembler directive respectively.

Algorithms(procedure) :
PASS 1
• Initialize location counter, entries of all tables as zero.
• Read statements from input file one by one.
• While next statement is not END statement
I. Tokenize or separate out input statement as label,numonic,operand1,operand2
II. If label is present insert label into symbol table.
III. If the statement is LTORG statement processes it by making it’s entry into literal
table, pool table and allocate memory.
IV. If statement is START or ORIGEN Process location counter accordingly.
V. If an EQU statement, assign value to symbol by correcting entry in symbol table.
VI. For declarative statement update code, size and location counter.
VII. Generate intermediate code.
VIII. Pass this intermediate code to pass -2.

Conclusions:

1 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Program:

#include<conio.h>
#include<stdio.h>
#define MAX 20
#include<string.h>

struct symbol
{
char sym[10];
int addr;
}S[MAX];

struct litab
{
char lit[10];
int addr;
}L[MAX];

void print_file(char *);


void print_symtab();
void print_littab();

char optab[]
[6]={"STOP","ADD","SUB","MULT","MOVER","MOVEM","COMP","BC","DIV","READ","
PRINT"};
char regtab[][5]={"AREG","BREG","CREG","DREG"};
char adtab[][7]={"START","END","ORIGIN","EQU","LTORG"};
char condtab[][4]={"LT","LE","EQ","GT","GE","ANY"};

FILE *fs,*ft;
char buffer[80],source[80],tok1[10],tok2[10],tok3[10],tok4[10],tok5[10];
int lc=0,sc=0,poolcnt=0,litcnt=0;
int pooltab[10];

int search_optab(char *s)


{
int i;
for(i=0;i<11;i++)
{
if(strcmp(optab[i],s)==0)
{
return i;

2 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

}
}
return -1;
}

int search_regtab(char *s)


{
int i;
for(i=0;i<4;i++)
{
if(strcmp(regtab[i],s)==0)
{
return i+1;
}
}
return -1;
}

int search_condtab(char *s)


{
int i;
for(i=0;i<6;i++)
{
if(strcmp(condtab[i],s)==0)
{
return (i+1);
}
}
return -1;
}

int search_adtab(char *s)


{
int i;
for(i=0;i<5;i++)
{
if(strcmp(adtab[i],s)==0)
{
return i+1;
}
}
return -1;
}

3 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

int search_symtab(char *s)


{
int i;
for(i=0;i<sc;i++)
{
if(strcmp(S[i].sym,s)==0)
{
return i;
}
}
return -1;
}

int search_littab(char *s)


{
int i;
for(i=pooltab[poolcnt];i<litcnt;i++)
{
if(strcmp(L[i].lit,s)==0)
{
return i;
}
}
return -1;
}

void pass1()
{
int p;
int n,i=0,j=0,k=0;

fs=fopen(source,"r");
if(fs==NULL)
{
printf("\n file does not exist!!!!");
getch();
exit(0);
}

ft=fopen("[Link]","w");
while(fgets(buffer,80,fs))
{
n=sscanf(buffer,"%s%s%s%s",tok1,tok2,tok3,tok4);
switch(n)

4 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

{
case 1: //ltorg,end
i=search_adtab(tok1);
if(i==2 || i==5)
{
for(j=pooltab[poolcnt];j<litcnt;j++)
{
L[j].addr=lc++;
}
lc--;
pooltab[++poolcnt]=litcnt;
fprintf(ft,"(AD, %02d)\n",i);
break;
}
case 2: //start
i=search_adtab(tok1);
if(i==1)
{
lc=atoi(tok2)-1;
fprintf(ft,"(AD, %02d) (C, %s)\n",i,tok2);
break;
}

case 3:i=search_optab(tok1);
if(i>=1 && i<=8)
{
tok2[strlen(tok2)-1]='\0';

k=search_regtab(tok2);

//mover areg,='5'
if(tok3[0]=='=')
{
j=search_littab(tok3);
if(j==-1)
{
strcpy(L[litcnt].lit,tok3);
fprintf(ft,"(IS, %02d)%d(L, %02d)\n",i,k,litcnt);
litcnt++;
}
else
{
fprintf(ft,"(IS, %02d) %d (L, %02d)\n",i,k,j);
}
break;

5 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

else//mover areg,A
{
p=search_symtab(tok3);
if(p==-1)
{
strcpy(S[sc].sym,tok3);
fprintf(ft,"(IS, %02d) %d (S, %02d)\n",i,k,sc);
sc++;
}
else
{
fprintf(ft,"(IS, %02d) %d (S, %02d)\n",i,k,p);
}
break;
}
}

//A DS 2
if(strcmp(tok2,"DS")==0)
{
p=search_symtab(tok1);
if(p==-1)
{
strcpy(S[sc].sym,tok1);
S[sc].addr=lc;
fprintf(ft,"(DL, 2) (C, %s)\n",tok3);
sc++;
}
else
{
S[p].addr=lc;
fprintf(ft,"(DL, 2) (C, %s)\n",tok3);
}
lc=lc+atoi(tok3)-1;
break;
}

}
lc++;
}
fcloseall();

6 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

void print_file(char *target)


{
FILE *fp;
fp=fopen(target,"r");
if(fp==NULL)
{
printf("\nfile does not exist!!!");
getch();
exit(0);
}
printf("\n\n");
while(fgets(buffer,80,fp))
{
printf("%s",buffer);
}
fclose(fp);
getch();
}

void print_littab()
{
int i;
printf("\n LITERAL\tADDRESS\n");
for(i=0;i<litcnt;i++)
{
printf("%s\t%d\n",L[i].lit,L[i].addr);
}
}

void print_symtab()
{
int p=0;
printf("\n SYMBOL\tADDRESS\n");
while(p<sc)
{
printf("%s\t%d\n",S[p].sym,S[p].addr);
p=p+1;
}
}

void main()
{
clrscr();
printf("\n enter source file name: \n");

7 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

scanf("%s",source);

printf("\n source code is: \n ");


print_file(source);

pass1();

printf("\n\n literal table: \n");


print_littab();

printf("\n\n symbol table: \n");


print_symtab();

printf("\n intermediate code is: \n");


print_file("[Link]");
getch();

getch();
}

//File 2- [Link]
//SOURCE FILE

START 200
MOVER AREG, ='5'
MOVEM BREG, ='1'
ADD BREG, A
LTORG
SUB CREG, B
A DS 2
B DS 2
END

//INTERMEDIATE CODE
(AD, 01) (C, 200)
(IS, 04) 1 (L, 00)
(IS, 05) 2 (L, 01)
(IS, 01) 2 (S, 00)
(AD, 05)
(IS, 02) 3 (S, 01)
(DL, 2) (C, 2)
(DL, 2) (C, 2)
(AD, 02)

8 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

OUTPUT
gcc pass1.c
./[Link]

Enter Source File Name:


[Link]

Source Code Is:

START 200
MOVER AREG, ='5'
MOVEM BREG, ='1'
ADD BREG, A
LTORG
SUB CREG, B
A DS 2
B DS 2
END

Literal Table:

LITERAL ADDRESS
='5' 203
='1' 204

Symbol Table:

SYMBOL ADDRESS
A 206
B 208

Intermediate Code Is:

(AD, 01) (C, 200)


(IS, 04) 1 (L, 00)
(IS, 05) 2 (L, 01)
(IS, 01) 2 (S, 00)
(AD, 05)
(IS, 02) 3 (S, 01)
(DL, 2) (C, 2)
(DL, 2) (C, 2)
(AD, 02)

//Assembler Pass 2

#include<stdio.h>
#include<conio.h>
#define MAX 20

struct symbol

9 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

{
char sym[10];
int addr;
}S[MAX]={
{"A",103},
{"B",106},
{"C",107}
};

char optab[]
[6]={"STOP","ADD","SUB","MULT","MOVER","MOVEM","COMP","BC","DIV","READ","PRINT"};
char regtab[][5]={"AREG","BREG","CREG","DREG"};
char condtab[][4]={"LT","LE","EQ","GT","GE","ANY"};
char adtab[][7]={"START","END","ORIGIN","EQU","LTORG"};

FILE *fs,*ft;
char source[20],buffer[80],tok1[10],tok2[10],tok3[10],tok4[10],tok5[10];
int lc,ec=0,sc=3;

int search_optab(char *s)


{
int i;
for(i=0;i<11;i++)
{
if(strcmp(optab[i],s)==0)
return i;
}
return(-1);
}
int search_symb(char *s)
{
int i;
for(i=0;i<sc;i++)
{
if(strcmp(S[i].sym,s)==0)
return i;
}
return(-1);
}
int search_regtab(char *s)
{
int i;
for(i=0;i<4;i++)
{
if(strcmp(regtab[i],s)==0)
return (i+1);
}
return(-1);
}
int search_condtab(char *s)
{
int i;
for(i=0;i<6;i++)
{
if(strcmp(condtab[i],s)==0)
return (i+1);

10 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

}
return(-1);
}
int search_adtab(char *s)
{
int i;
for(i=0;i<5;i++)
{
if(strcmp(adtab[i],s)==0)
return (i+1);
}
return(-1);
}
void print_file(char *target)
{
FILE *fp;
fp=fopen(target,"r");
if(fp==NULL)
{
printf("\nError In Opening File");
getch();
exit(0);
}
printf("\n\n");
while(fgets(buffer,80,fp))
{
printf("%s",buffer);
}
//printf("%d",lc);
fclose(fp);
}
void passtwo()
{
int i,j,k,n,p;

char temp[20];
if((fs=fopen("[Link]","r"))==NULL)
{
printf("\n\nError In Opening [Link]");
getch();
exit(0);
}
if((ft=fopen("[Link]","w"))==NULL)
{
printf("\n\nError In Opening [Link]");
getch();
exit(0);
}
lc=0;
while(fgets(buffer,80,fs))
{
n=sscanf(buffer,"%s%s%s%s%s",tok1,tok2,tok3,tok4,tok5);
switch(n)
{
case 4:
if(strcmp(tok1,"(AD,")==0)

11 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

{
tok4[strlen(tok4)-1]='\0';
lc=atoi(tok4)-1;
break;
}
if(strcmp(tok1,"(DL,")==0)
{
tok2[strlen(tok2)-1]='\0';
tok4[strlen(tok4)-1]='\0';
i=atoi(tok2);
j=atoi(tok4);
if(i==2) //A DS 2
{
for(k=0;k<j;k++)
{
fprintf(ft,"%d)\n",lc++);
}
lc--;
}
else //ONE DC 1
{
fprintf(ft,"%d) %d\n",lc,j);
}
}
break;

case 5:
tok2[strlen(tok2)-1]='\0';
tok5[strlen(tok5)-1]='\0';
i=atoi(tok2);
j=atoi(tok3);
k=atoi(tok5);
if(strcmp(tok4,"(S,")==0)
{
fprintf(ft,"%d) %02d %d %03d\n",lc,i,j,S[k].addr);
}
break;

} //switch

lc++;

} //while

fcloseall();
}
void print_symb()
{
int p=0;

printf("\n\tsymbol\taddress");

while(p<sc)
{
printf("\n\t%s\t%d",S[p].sym,S[p].addr);
p=p+1;

12 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

}
}
void main()
{
clrscr();
printf("\n\n\tSYMBOL TABL[Link]\n");
print_symb();
printf("\n\n\n\tINTERMEDIATE CO[Link]\n");
print_file("[Link]");
getch();

passtwo();
printf("\n\n\tTARGET CO[Link]\n");
print_file("[Link]");
getch();
}

Output of Assembler Pass 2

SYMBOL TABL[Link]

symbol address
A 103
B 106
C 107

INTERMEDIATE CO[Link]

(AD, 01) (C, 100)


(IS, 01) 1 (S, 0)
(IS, 02) 2 (S, 1)
(IS, 05) 2 (S, 2)
(DL, 2) (C, 3)
(DL, 1) (C, 2)
(DL, 2) (C, 3)
(IS, 03) 2 (S, 2)
(IS, 08) 3 (S, 1)
(AD, 02)

TARGET CO[Link]

100) 01 1 103
101) 02 2 106
102) 05 2 107
103)
104)
105)
106) 2
107)
108)
109)
110) 03 2 107
111) 08 3 106

13 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Program using python

import os
LC=0 #location counter initialization
"""
mnemonic dictionary elements are:
Key is mnemonic e.g. "STOP"
Value of that key is a tuple consiting of opcode value, instruction class or type and number of
operands required for that mnemonic
e.g. "STOP":('00','IS',0)
This states that 'STOP' is a mnemonic whereas value tuple consisting of '00' is opcode, 'IS' is
instruction type, 0 is number of operands that mnemonics required.
"""
mnemonics={'STOP':('00','IS',0),'ADD':('01','IS',2),'SUB':('02','IS',2),'MUL':
('03','IS',2),'MOVER':('04','IS',2),'MOVEM':('05','IS',2),'COMP':('06','IS',2),'BC':
('07','IS',2),'DIV':('08','IS',2),'READ':('09','IS',1),'PRINT':('10','IS',1),'LTORG':
('05','AD',0),'ORIGIN':('03','AD',1),'START':('01','AD',1),'EQU':('04','AD',2),'DS':
('01','DL',1),'DC':('02','DL',1),'END':('AD',0)}
file=open("[Link]") #Enter input file with complete path if not in same directory

ifp=open("inter_code.txt","a") #output file having intermediate code


[Link](0) #cleaning file to remove previous data
REG={'AREG':1,'BREG':2,'CREG':3,'DREG':4} #Registers
lit=open("[Link]","a+") #literals and their address containing file
[Link](0)
tmp=open("[Link]","a+")
[Link](0)
symtab={} #Sybol Table
pooltab=[ ] #Pool Table
words=[ ]

#prints literal table


def littab():
print("literal table:")
[Link](0,0)

14 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

for x in lit:
print(x)

#prints pool table


def pooltab2():
global pooltab
print("Pool Table:")
print(pooltab)
#prints symbol table
def symbol():
global symtab
print("Symbol Table:")
print(symtab)

#handles END directive


def END():
global LC
pool=0
z=0
[Link]("\t(AD,02)\n")
[Link](0,0)
for x in lit:
if "**" in x:
pool+=1
if pool==1:
[Link](z)
y=[Link]()
[Link](y[0]+"\t"+str(LC)+"\n")
LC+=1
else:
[Link](x)
z+=1
[Link](0)
[Link](0,0)
for x in tmp:
[Link](x)
[Link](0)

#handles LTORG mnemonic


def LTORG():
global LC
pool=0
z=0
[Link](0,0)
x=[Link]()
i=0
while(i<len(x)):
f=[]
if("**" in x[i]):
j=0
pool+=1
if pool==1:

15 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

[Link](z)
while(x[i][j]!="'"):
j+=1
j+=1
while(x[i][j]!="'"):
[Link](x[i][j])
j+=1
if(i!=len(x)-1):
[Link]("\t(AD,05)\t(DL,02)(C,"+str(f[0])+")\n")
y=x[i].split()
[Link](y[0]+"\t"+str(LC)+"\n")
LC+=1
[Link](str(LC))
else:
[Link]("\t(AD,05)\t(DL,02)(C,"+str(f[0])+")\n")
y=x[i].split()
[Link](y[0]+"\t"+str(LC)+"\n")
LC+=1
else:
[Link](x[i])
z+=1
i+=1
[Link](0)
[Link](0,0)
for x in tmp:
[Link](x)
[Link](0)

#handles ORIGIN mnemonic


def ORIGIN(addr):
global LC
[Link]("\t(AD,03)\t(C,"+str(addr)+")\n")
LC =int(addr)

#handles DS mnemonic
def DS(size):
global LC
[Link]("\t(DL,01)\t(C,"+size+")\n")
LC=LC+int(size)

#handles DC mnemonic
def DC(value):
global LC
[Link]("\t(DL,02)\t(C,"+value+")\n")
LC+=1

'''
def EQU(words):
global symindex
if words[2] in [Link]():
z=symtab[words[2]]
if words[0] not in [Link]():
symtab[words[0]]=(z[0],symindex)
symindex+=1

16 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

else:
w=symtab[words[0]]
symtab[words[0]]=(z[0],w[-1])

#else:#error words[2] not defined


'''
#identifies type of operands i.e. registers, literals, symbols and add approprite data in intermediate code file,
literal table and symbol table as well as pool table.
def OTHERS(mnemonic,k):
global words
global mnemonics
global symtab
global LC,symindex
z=mnemonics[mnemonic]
[Link]("\t("+z[1]+","+z[0]+")\t")
i=0
y=z[-1]
#print("y="+str(y))
for i in range(1,y+1):
words[k+i]=words[k+i].replace(",","")
if(words[k+i] in [Link]()):
[Link]("(RG,"+str(REG[words[k+i]])+")")
elif("=" in words[k+i]):
#print(words[k+i])
[Link](0,2)
[Link](words[k+i]+"\t**\n")
[Link](0,0)
x=[Link]()
#print(len(x))
[Link]("(L,"+str(len(x))+")")
else:
#print(words,symtab)
if(words[k+i] not in [Link]()):
symtab[words[k+i]]=("**",symindex)
[Link]("(S,"+str(symindex)+")")
symindex+=1
else:
w=symtab[words[k+i]]
[Link]("(S,"+str(w[-1])+")")
#print(symtab)
[Link]("\n")
LC+=1

#idenifies mnemonic and redirect to resepective function


def detect_mn(k):
global words,LC
if(words[k]=="START"):
LC=int(words[1])
[Link]("\t(AD,01)\t(C,"+str(LC)+')\n')
elif(words[k]=='END'):
END()
elif(words[k]=="LTORG"):
LTORG()
elif(words[k]=="ORIGIN"):
ORIGIN(words[k+1])
elif(words[k]=="DS"):

17 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

DS(words[k+1])
elif(words[k]=="DC"):
DC(words[k+1])
#elif(words[k]=="EQU"):
#EQU(words)
else:
OTHERS(words[k],k)
littab()
pooltab2()
symbol()

#actual code execution starts from here


symindex=0
for line in file:
#print(line)
words=[Link]()
#print(words)
if(LC>0):
[Link](str(LC))
print("LC=",LC)
print(line)
print(words)
k=0

if words[0] in [Link]():
print("Mnemonic:",words[0])
val=mnemonics[words[0]]
k=0
detect_mn(k)
else:
print("Label:",words[0],"Mnemonic:",words[1])
if words[k] not in [Link]():
symtab[words[k]]=(LC,symindex)
#[Link]("\t(S,"+str(symindex)+")\t")
symindex+=1
symbol()
else:
#print(words)
x=symtab[words[k]]
if x[0]=="**":
print("yes")
symtab[words[k]]=(LC,x[1])
#[Link]("\t(S,"+str(symindex)+")\t")
symbol()
k=1
detect_mn(k)
#print(symtab)
#print(pooltab)
[Link]()
[Link]()
[Link]()
sym=open("[Link]","a+")
[Link](0)
for x in symtab:
[Link](x+"\t"+str(symtab[x][0])+"\n")
[Link]()

18 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

pool=open("[Link]","a+")
[Link](0)
for x in pooltab:
[Link](str(x)+"\n")
[Link]()
if [Link]("[Link]")==True:
[Link]("[Link]")

Input file

START 100
A DC 10
MOVER AREG, B
MOVEM BREG, ='1'
ADD AREG, ='2'
SUB BREG, ='1'
B DC 20
ORIGIN 300
LTORG
MOVER AREG, NUM
MOVER CREG, LOOP
ADD BREG, ='1'
NUM DS 5
LOOP DC 10
END

Sample output:
LC= 0
START 100

['START', '100']
Mnemonic: START
literal table:
Pool Table:
[]
Symbol Table:
{}
LC= 100
A DC 10

['A', 'DC', '10']


Label: A Mnemonic: DC
Symbol Table:
{'A': (100, 0)}
literal table:
Pool Table:
[]
Symbol Table:

19 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

{'A': (100, 0)}


LC= 101
MOVER AREG, B

['MOVER', 'AREG,', 'B']


Mnemonic: MOVER
literal table:
Pool Table:
[]
Symbol Table:
{'A': (100, 0), 'B': ('**', 1)}
LC= 102
MOVEM BREG, ='1'

['MOVEM', 'BREG,', "='1'"]


Mnemonic: MOVEM
literal table:
='1' **

Pool Table:
[]
Symbol Table:
{'A': (100, 0), 'B': ('**', 1)}
LC= 103
ADD AREG, ='2'

['ADD', 'AREG,', "='2'"]


Mnemonic: ADD
literal table:
='1' **

='2' **

Pool Table:
[]
Symbol Table:
{'A': (100, 0), 'B': ('**', 1)}
LC= 104
SUB BREG, ='1'

['SUB', 'BREG,', "='1'"]


Mnemonic: SUB
literal table:
='1' **

='2' **

='1' **

Pool Table:
[]
Symbol Table:
{'A': (100, 0), 'B': ('**', 1)}
LC= 105

20 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

B DC 20

['B', 'DC', '20']


Label: B Mnemonic: DC
yes
Symbol Table:
{'A': (100, 0), 'B': (105, 1)}
literal table:
='1' **

='2' **

='1' **

Pool Table:
[]
Symbol Table:
{'A': (100, 0), 'B': (105, 1)}
LC= 106
ORIGIN 300

['ORIGIN', '300']
Mnemonic: ORIGIN
literal table:
='1' **

='2' **

='1' **

Pool Table:
[]
Symbol Table:
{'A': (100, 0), 'B': (105, 1)}
LC= 300
LTORG

['LTORG']
Mnemonic: LTORG
literal table:
='1' 300

='2' 301

='1' 302

Pool Table:
[0]
Symbol Table:
{'A': (100, 0), 'B': (105, 1)}
LC= 303
MOVER AREG, NUM

['MOVER', 'AREG,', 'NUM']

21 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Mnemonic: MOVER
literal table:
='1' 300

='2' 301

='1' 302

Pool Table:
[0]
Symbol Table:
{'A': (100, 0), 'B': (105, 1), 'NUM': ('**', 2)}
LC= 304
MOVER CREG, LOOP

['MOVER', 'CREG,', 'LOOP']


Mnemonic: MOVER
literal table:
='1' 300

='2' 301

='1' 302

Pool Table:
[0]
Symbol Table:
{'A': (100, 0), 'B': (105, 1), 'NUM': ('**', 2), 'LOOP': ('**', 3)}
LC= 305
ADD BREG, ='1'

['ADD', 'BREG,', "='1'"]


Mnemonic: ADD
literal table:
='1' 300

='2' 301

='1' 302

='1' **

Pool Table:
[0]
Symbol Table:
{'A': (100, 0), 'B': (105, 1), 'NUM': ('**', 2), 'LOOP': ('**', 3)}
LC= 306
NUM DS 5

['NUM', 'DS', '5']


Label: NUM Mnemonic: DS
yes
Symbol Table:
{'A': (100, 0), 'B': (105, 1), 'NUM': (306, 2), 'LOOP': ('**', 3)}

22 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

literal table:
='1' 300

='2' 301

='1' 302

='1' **

Pool Table:
[0]
Symbol Table:
{'A': (100, 0), 'B': (105, 1), 'NUM': (306, 2), 'LOOP': ('**', 3)}
LC= 311
LOOP DC 10

['LOOP', 'DC', '10']


Label: LOOP Mnemonic: DC
yes
Symbol Table:
{'A': (100, 0), 'B': (105, 1), 'NUM': (306, 2), 'LOOP': (311, 3)}
literal table:
='1' 300

='2' 301

='1' 302

='1' **

Pool Table:
[0]
Symbol Table:
{'A': (100, 0), 'B': (105, 1), 'NUM': (306, 2), 'LOOP': (311, 3)}
LC= 312
END
['END']
Mnemonic: END
literal table:
='1' 300

='2' 301

='1' 302

='1' 312

Pool Table:
[0, 3]
Symbol Table:
{'A': (100, 0), 'B': (105, 1), 'NUM': (306, 2), 'LOOP': (311, 3)}

23 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Name of the Student: ______________________________________ Roll no: ___


CLASS: - T.E. [Computer Engineering] Division: Course: - Lab Practices-I
Assignment-2
Design suitable data structures and implement Pass-I and Pass-II of a two-pass macro- processor.

Marks: /10
Date of Performance: Sign with Date

/ / 2023

Aim: Design suitable data structures and implement Pass-I and Pass-II of a two-pass macro- processor.
Objective:
1) To Identify and create the data structures required in the design of macro processor
2) Implement Pass-I and Pass-II of a two-pass macro- processor using C++
Theory :
 In Pass-I the macro definitions are searched and stored in the macro definition table and the entry is
made in macro name table
 In Pass-II the macro calls are identified and the arguments are placed in the appropriate place and the
macro calls are replaced by macro definitions.
Pass 1:-
• The input macro source program.
• The output macro source program to be used by Pass2.
• Macro-Definition Table (MDT), to store the body of macro definition .
• Macro-Definition Table Counter (MDTC), to mark next available entry MDT.
• Macro- Name Table (MNT) - store names of macros.
• Macro Name Table counter (MNTC) - indicate the next available entry in MNT.
• Argument List Array (ALA) - substitute index markers for dummy arguments before storing a macro-
definition.

24 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Pass 2:-
• The input is from Pass1.
• The output is expanded source to be given to assembler.
• MDT and MNT are created by Pass1.
• Macro-Definition Table Pointer (MDTP), used to indicate the next line of text to be used
during macro expansion.
• Argument List Array (ALA), used to substitute macro call arguments for the index markers in
the stored macro-definitions.
Design of two pass Macro processor
PASS I - ALGORITHM
• Pass1 of macro processor makes a line-by-line scan over its input.
• Set MDTC = 1 as well as MNTC = 1.
• Read next line from input program.
• If it is a MACRO pseudo-op, the entire macro definition except this (MACRO) line is stored in
MDT.
• The name is entered into Macro Name Table along with a pointer to the first location of MDT
entry of the definition.
• When the END pseudo-op is encountered all the macro-definitions have been processed, so
control is transferred to pass2

25 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Figure : Pass I processing Macro Definitions

PASS II - ALGORITHM
• This algorithm reads one line of input program at a time.
• for each Line it checks if op-code of that line matches any of the MNT entry.
• When match is found (i.e. when call is pointer called MDTF to corresponding macro
definitions stored in MDT.
• The initial value of MDTP is obtained from MDT index field of MNT entry.

26 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

•The macro expander prepares the ALA consisting of a table of dummy argument indices &
corresponding arguments to the call.
•Reading proceeds from the MDT, as each successive line is read, The values form the argument
list one substituted for dummy arguments indices in the macro definition.
• Reading MEND line in MDT terminates expansion of macro & scanning continues from the
input file.
• When END pseudo-op encountered , the expanded source program is given to the assembler.

Figure : Pass II processing Macro calls and expansion

27 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Conclusions:

28 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

/*--------MACRO PROGRAM--------*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
#include<process.h>
#include<stdlib.h>

typedef struct mnt //Macro Name Table


{
char mname[10];
int mdt_index;
}mnt;

char mdt[100][40]; //Macro Defintion Table


mnt mn[10];

void main()
{
int mdt_pntr=0,mnt_pntr=0,v_pntr=0,i,j,loc_cnt=0,flag=0;
char temp[100],tkn[10][10],v[15][15],temp1[100],tkn1[10][10];
FILE *fp,*fp1;
clrscr();
fp=fopen("[Link]","r");
fp1=fopen("[Link]","w+");

if (fp==NULL)
{
printf("Cannot open output file.\n");
exit(0);
}

while(fgets(temp,40,fp))
{

for(i=0;i<4;i++)
strcpy(tkn[i],"");
sscanf(temp,"%s %s %s %s",tkn[0],tkn[1],tkn[2],tkn[3]);

if(strcmpi(tkn[0],"macro")!=0)
printf("%s %s %s %s\t\t\n",tkn[0],tkn[1],tkn[2],tkn[3]); //
as it is print bcoz assebler statement

else
{
for(i=0;i<4;i++)
strcpy(tkn[i],"");
fgets(temp,40,fp);
sscanf(temp,"%s %s %s %s",tkn[0],tkn[1],tkn[2],tkn[3]);
strcpy(mdt[mdt_pntr++],temp);

29 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

strcpy(mn[mnt_pntr].mname,tkn[0]);
mn[mnt_pntr].mdt_index=mdt_pntr-1;
mnt_pntr++;
//**************************************************

for(i=1;i<4;i++) // storing parameters in v[] array


{
if(tkn[i][0]=='&')
{
strcpy(v[v_pntr],tkn[i]);
v_pntr++;
}
}

//*************************
while(fgets(temp,40,fp))
{
for(i=0;i<4;i++)
strcpy(tkn[i],"");
sscanf(temp,"%s %s %s %s",tkn[0],tkn[1],tkn[2],tkn[3]);

if(strcmp(tkn[0],"mend")==0) //if mend,store in MDT


{
strcpy(mdt[mdt_pntr++],temp);
loc_cnt++;
break;
}

for(i=0;i<v_pntr;i++)
{
if(strcmp(tkn[2],v[i])==0)
{ sprintf(temp,"%s %s %d %s \n",tkn[0],tkn[1],i,tkn[3]);
strcpy(mdt[mdt_pntr++],temp);
sprintf(temp,"%s %s %d %s\n",tkn[0],tkn[1],i,tkn[3]);

break;
}
}

}
v_pntr=0;
}
}

printf("\n\n\t\t\tMNT TABLE\n\n");
printf("\tmnt index\tmnt name\tmdt index\n");
printf("___________________________________________________
___\n\n");
for(i=0;i<mnt_pntr;i++)
printf("\t%d\t\t%s\t\t\t%d\n",i,mn[i].mname,mn[i].mdt_index
);

30 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

getch();
printf("\n\n\n");
printf("\t\t\tMDT TABLE\n\n");
printf("\tmdtindex \t macro def\n");
printf("___________________________________________\n\n");
for(i=0;i<mdt_pntr;i++)
{
fprintf(fp1,"\t%d\t\t%s",i,mdt[i]);
printf("\t%d\t\t%s",i,mdt[i]);
}
getch();
fcloseall();

//*--------- PASS-2 -----------


clrscr();
printf("\n\t\t----Expansion of macro---- \n\n");
fp=fopen("[Link]","r");
fp1=fopen("[Link]","r");
printf(fgets(temp,40,fp));
while(fgets(temp,40,fp)) //Skipping all macros
{
if(strcmp("mend\n",temp)==0)
{
loc_cnt--;
}
if(loc_cnt==0)
break;
}
while(fgets(temp,40,fp))
{ flag=0; rewind(fp1);
for(i=0;i<4;i++)
strcpy(tkn[i],"");
sscanf(temp,"%s %s %s %s",tkn[0],tkn[1],tkn[2],tkn[3]);
for(i=0;i<mnt_pntr;i++) //Checking with all macro
names
{
if(strcmp(mn[i].mname,tkn[0])==0) //if macro
{flag=1;
while(fgets(temp1,40,fp1)) //use it's def.
{

sscanf(temp1,"%s %s %s %s",tkn1[0],tkn1[1],tkn1[2],
tkn1[3],tkn1[4]);
if(atoi(tkn1[0])==mn[i].mdt_index) //pointing to
def.
{
while(fgets(temp1,40,fp1))
{
sscanf(temp1,"%s %s %s %s",tkn1[0],tkn1[1],tkn1[2],
tkn1[3],tkn1[4]);
if (strcmp(tkn1[1],"mend")==0)
break;

31 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

if(strcmp(tkn1[3],"0")==0)
{
sprintf(temp1,"%s %s %s %s",tkn1[1],tkn1[2]
,tkn[1]);
}
if(strcmp(tkn1[3],"1")==0)
{
sprintf(temp1,"%s %s %s %s",tkn1[1],tkn1[2]
,tkn[2]);
}
if(strcmp(tkn1[3],"2")==0)
{
sprintf(temp1,"%s %s %s %s",tkn1[1],tkn1[2]
,tkn[3]);
}
printf("%s\n",temp1);

}
flag=1;
}

}
break;
}

}
if(flag==0)
printf("%s",temp);
}

getch();
}

32 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

PROGRAM:[Link]
start 100
mover bregs asd
sub aregs =6
add aregs =5
sub aregs =6
sub1 1 2 32
ltorg
movem cregs =3
mover bregs asd
origin 103
sub aregs =6
mover bregs sd
sd dc 3
add1 44 55
asd ds 2
sub1 98 99 78
end

INTERMEDIATE FILE

0 sub1 &a &b &c


1 mover aregs 0
2 mover aregs 1
3 add bregs 2
4 mend
5 add1 &c &d
6 mover aregs 1
7 add bregs 0
8 mend

33 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

OUTPUT
start 100
mover bregs asd
sub aregs =6
add aregs =5
sub aregs =6
sub1 1 2 32
ltorg
movem cregs =3
mover bregs asd
origin 103
sub aregs =6
mover bregs sd
sd dc 3
add1 44 55
asd ds 2
sub1 98 99 78
end

MNT TABLE

mnt index mnt name mdt index


______________________________________________________

0 sub1 0
1 add1 5

MDT TABLE

mdtindex macro def


___________________________________________

0 sub1 &a &b &c


1 mover aregs 0
2 mover aregs 1
3 add bregs 2
4 mend
5 add1 &c &d
6 mover aregs 1
7 add bregs 0
8 mend

34 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

----Expansion of macro----

start 100
mover bregs asd
sub aregs =6
add aregs =5
sub aregs =6
mover aregs 1
mover aregs 2
add bregs 32
ltorg
movem cregs =3
mover bregs asd
origin 103
sub aregs =6
mover bregs sd
sd dc 3
mover aregs 55
add bregs 44
asd ds 2
mover aregs 98
mover aregs 99
add bregs 78
end

Name of the Student: ______________________________________ Roll no: ___


CLASS: - T.E. [Computer Engineering ] Division: B Course: - Lab Practices-I
Assignment-3
Write a program to simulate CPU Scheduling Algorithms: FCFS, SJF (Preemptive), Priority (Non-
Preemptive) and Round Robin (Preemptive).

Date of Performance: Sign with Date Marks: /10

/ / 2023

Aim: Write a program to simulate CPU Scheduling Algorithms: FCFS, SJF (Preemptive), Priority (Non-
Preemptive) and Round Robin (Preemptive).
Objectives: Implement CPU scheduling algorithms FCFS, SJF (Preemptive), Priority (Non-Preemptive) and
Round Robin (Preemptive) using Python.
Theory:
A Process Scheduler schedules different processes to be assigned to the CPU based on particular scheduling
35 | Department Computer Engineering, SIT, Lonavala
algorithms.
 First-Come, First-Served (FCFS) Scheduling
Downloaded by Adinath Sonawane (adinaths109@[Link])
 Shortest-Job-Next (SJN) Scheduling or Shortest-Job-First (SJF) Scheduling
lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Algorithm
Step 1: Start the process
Step 2: Accept the number of processes in the ready Queue
Step 3: For each process in the ready Q, assign the process id and accept the CPU burst time
Step 4: Set the waiting of the first process as ‘0’ and its burst time as its turnaround time
Step 5: for each process in the Ready Q calculate
(a) Waiting time for process(n)= waiting time of process (n-1) + Burst time of process(n-1)
(b) Turnaround time for Process(n)= waiting time of Process(n)+ Burst time for process(n)
Step 6: Calculate
(a) Average waiting time = Total waiting Time / Number of process

(b) Average Turnaround time = Total Turnaround Time / Number of process Step 7: Stop the process

2) Shortest-Job-Next (SJN) Scheduling or Shortest-Job-First (SJF) Scheduling


 This is also known as shortest job first, or SJF
 This is a non-preemptive, pre-emptive scheduling algorithm.
 Best approach to minimize waiting time.
 Easy to implement in Batch systems where required CPU time is known in advance.
 Impossible to implement in interactive systems where required CPU time is not known.
 The processer should know in advance how much time process will take.
Algorithm
Step 1: Start the process
Step 2: Accept the number of processes in the ready Queue
Step 3: For each process in the ready Q, assign the process id and accept the CPU burst time
Step 4: Start the Ready Q according the shortest Burst time by sorting according to lowest to
highest burst time.
Step 5: Set the waiting time of the first process as ‘0’ and its turnaround time as its burst time.
Step 6: For each process in the ready queue, calculate
(c) Waiting time for process(n)= waiting time of process (n-1) + Burst time of process(n-1)
(d) Turnaround time for Process(n)= waiting time of Process(n)+ Burst time for process(n)
Step 6: Calculate
(c) Average waiting time = Total waiting Time / Number of process
(d) Average Turnaround time = Total Turnaround Time / Number of process
36 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Step 7: Stop the process

3) Priority Scheduling
 Priority scheduling is a non-preemptive algorithm and one of the most common
scheduling algorithms in batch systems.
 Each process is assigned a priority. Process with highest priority is to be executed first
and so on.
 Processes with same priority are executed on first come first served basis.
 Priority can be decided based on memory requirements, time requirements or any other
resource requirement.
Algorithm
Step 1: Start the process
Step 2: Accept the number of processes in the ready Queue
Step 3: For each process in the ready Q, assign the process id and accept the CPU burst time,
priority
Step 4: Start the Ready Q according the priority by sorting according to lowest to
highest burst time and process.
Step 5: Set the waiting time of the first process as ‘0’ and its turnaround time as its burst time.
Step 6: For each process in the ready queue, calculate
(e) Waiting time for process(n)= waiting time of process (n-1) + Burst time of process(n-1)
(f) Turn around time for Process(n)= waiting time of Process(n)+ Burst time for process(n)
Step 6: Calculate
(g) Average waiting time = Total waiting Time / Number of process
(h) Average Turnaround time = Total Turnaround Time / Number of process
Step 7: Stop the process

4) Round Robin(RR) Scheduling


 Round Robin is the preemptive process scheduling algorithm.
 Each process is provided a fix time to execute, it is called a quantum.
 Once a process is executed for a given time period, it is preempted and other process
executes for a given time period.
 Context switching is used to save states of preempted processes.

37 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Algorithm
Step 1: Start the process
Step 2: Accept the number of processes in the ready Queue and time quantum (or) time slice
Step 3: For each process in the ready Q, assign the process id and accept the CPU burst time
Step 4: Calculate the no. of time slices for each process where
No. of time slice for process(n) = burst time process(n)/time slice
Step 5: If the burst time is less than the time slice then the no. of time slices =1.
Step 6: Consider the ready queue is a circular Q, calculate
(a) Waiting time for process(n) = waiting time of process(n-1)+ burst time of process(n-1 ) +
the time difference in getting the CPU from process(n-1)
(b) Turnaround time for process(n) = waiting time of process(n) + burst time of process(n)+
the time difference in getting CPU from process(n).
Step 7: Calculate
(e) Average waiting time = Total waiting Time / Number of process
(f) Average Turnaround time = Total Turnaround Time / Number of process
Step 8: Stop the process.

Conclusions:

38 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

1. FCFS PROGRAM
#include<iostream>
using namespace std;
int main()
{ int n,bt[20],wt[20],tat[20],avwt=0,avtat=0,i,j;
cout<<"Enter total number of processes(maximum 20):";
cin>>n;

cout<<"\nEnter Process Burst Time aka DURATION \n";


for(i=0;i<n;i++)
{
cout<<"P["<<i+1<<"]:";
cin>>bt[i];
}
wt[0]=0; //waiting time for first process is 0
//calculating waiting time
for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];
}
cout<<"\nProcess\t\tBurst Time\tWaiting Time\tTurnaround Time";
//calculating turnaround time
for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i];
avwt+=wt[i];
avtat+=tat[i];
cout<<"\nP["<<i+1<<"]"<<"\t\t"<<bt[i]<<"\t\t"<<wt[i]<<"\t\
t"<<tat[i];
}
avwt/=i;
avtat/=i;
cout<<"\n\nAverage Waiting Time:"<<avwt;
cout<<"\nAverage Turnaround Time:"<<avtat;

return 0;
}

OR
//C++ program for implementation of FCFS
// scheduling
#include<iostream>

39 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

using namespace std;

// Function to find the waiting time for all


// processes
void findWaitingTime(int processes[], int n,
int bt[], int wt[])
{
// waiting time for first process is 0
wt[0] = 0;

// calculating waiting time


for (int i = 1; i < n ; i++ )
wt[i] = bt[i-1] + wt[i-1] ;
}

// Function to calculate turn around time


void findTurnAroundTime( int processes[], int n,
int bt[], int wt[], int tat[])
{
// calculating turnaround time by adding
// bt[i] + wt[i]
for (int i = 0; i < n ; i++)
tat[i] = bt[i] + wt[i];
}

//Function to calculate average time


void findavgTime( int processes[], int n, int bt[])
{
int wt[n], tat[n], total_wt = 0, total_tat = 0;

//Function to find waiting time of all processes


findWaitingTime(processes, n, bt, wt);

//Function to find turn around time for all processes


findTurnAroundTime(processes, n, bt, wt, tat);

//Display processes along with all details


cout << "Processes "<< " Burst time "
<< " Waiting time " << " Turn around time\n";

// Calculate total waiting time and total turn


// around time
for (int i=0; i<n; i++)
{
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
cout << " " << i+1 << "\t\t" << bt[i] <<"\t "
<< wt[i] <<"\t\t " << tat[i] <<endl;
}

cout << "Average waiting time = "


<< (float)total_wt / (float)n;

40 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

cout << "\nAverage turn around time = "


<< (float)total_tat / (float)n;
}

// Driver code
int main()
{
//process id's
int processes[] = { 1, 2, 3};
int n = sizeof processes / sizeof processes[0];

//Burst time of all processes


int burst_time[] = {10, 5, 8};

findavgTime(processes, n, burst_time);
return 0;
}

OUTPUT:
Enter total number of processes(maximum 20):5

Enter Process Burst Time aka DURATION


P[1]:4
P[2]:3
P[3]:2
P[4]:1
P[5]:5

Process Burst Time Waiting Time Turnaround Time


P[1] 4 0 4
P[2] 3 4 7
P[3] 2 7 9
P[4] 1 9 10
P[5] 5 10 15

Average Waiting Time:6


Average Turnaround Time:9

41 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Program 2: SJF scheduling


#include <iostream>
using namespace std;

int main() {

// Matrix for storing Process Id, Burst


// Time, Average Waiting Time & Average
// Turn Around Time.
int A[100][4];
int i, j, n, total = 0, index, temp;
float avg_wt, avg_tat;

cout << "Enter number of process: ";


cin >> n;

cout << "Enter Burst Time:" << endl;

// User Input Burst Time and alloting Process Id.


for (i = 0; i < n; i++) {
cout << "P" << i + 1 << ": ";
cin >> A[i][1];
A[i][0] = i + 1;
}

// Sorting process according to their Burst Time.


for (i = 0; i < n; i++) {

42 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

index = i;
for (j = i + 1; j < n; j++)
if (A[j][1] < A[index][1])
index = j;
temp = A[i][1];
A[i][1] = A[index][1];
A[index][1] = temp;

temp = A[i][0];
A[i][0] = A[index][0];
A[index][0] = temp;
}

A[0][2] = 0;
// Calculation of Waiting Times
for (i = 1; i < n; i++) {
A[i][2] = 0;
for (j = 0; j < i; j++)
A[i][2] += A[j][1];
total += A[i][2];
}

avg_wt = (float)total / n;
total = 0;
cout << "P BT WT TAT" << endl;

// Calculation of Turn Around Time and printing the


// data.
for (i = 0; i < n; i++) {
A[i][3] = A[i][1] + A[i][2];
total += A[i][3];

43 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

cout << "P" << A[i][0] << " " << A[i][1] << " " << A[i][2] << " " << A[i][3] <<
endl;
}

avg_tat = (float)total / n;
cout << "Average Waiting Time= " << avg_wt << endl;
cout << "Average Turnaround Time= " << avg_tat << endl;
}

Output:

Enter number of process: 5


Enter Burst Time:
P1: 4
P2: 5
P3: 3
P4: 2
P5: 1
P BT WT TAT
P5 1 0 1
P4 2 1 3
P3 3 3 6
P1 4 6 10
P2 5 10 15
Average Waiting Time= 4
Average Turnaround Time= 7

44 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Program 3: Round Robin Scheduling


// C++ program for implementation of RR scheduling
#include<iostream>
using namespace std;

// Function to find the waiting time for all


// processes
void findWaitingTime(int processes[], int n,
int bt[], int wt[], int quantum)
{
// Make a copy of burst times bt[] to store remaining
// burst times.
int rem_bt[n];
for (int i = 0 ; i < n ; i++)
rem_bt[i] = bt[i];

int t = 0; // Current time

// Keep traversing processes in round robin manner


// until all of them are not done.
while (1)
{
bool done = true;

// Traverse all processes one by one repeatedly


for (int i = 0 ; i < n; i++)

45 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

{
// If burst time of a process is greater than 0
// then only need to process further
if (rem_bt[i] > 0)
{
done = false; // There is a pending process

if (rem_bt[i] > quantum)


{
// Increase the value of t i.e. shows
// how much time a process has been processed
t += quantum;

// Decrease the burst_time of current process


// by quantum
rem_bt[i] -= quantum;
}

// If burst time is smaller than or equal to


// quantum. Last cycle for this process
else
{
// Increase the value of t i.e. shows
// how much time a process has been processed
t = t + rem_bt[i];

// Waiting time is current time minus time


// used by this process
wt[i] = t - bt[i];

// As the process gets fully executed

46 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

// make its remaining burst time = 0


rem_bt[i] = 0;
}
}
}

// If all processes are done


if (done == true)
break;
}
}

// Function to calculate turn around time


void findTurnAroundTime(int processes[], int n,
int bt[], int wt[], int tat[])
{
// calculating turnaround time by adding
// bt[i] + wt[i]
for (int i = 0; i < n ; i++)
tat[i] = bt[i] + wt[i];
}

// Function to calculate average time


void findavgTime(int processes[], int n, int bt[], int quantum)
{
int wt[n], tat[n], total_wt = 0, total_tat = 0;

// Function to find waiting time of all processes


findWaitingTime(processes, n, bt, wt, quantum);

// Function to find turn around time for all processes

47 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

findTurnAroundTime(processes, n, bt, wt, tat);

// Display processes along with all details


cout << "PN\t "<< " \tBT "
<< " WT " << " \tTAT\n";

// Calculate total waiting time and total turn


// around time
for (int i=0; i<n; i++)
{
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
cout << " " << i+1 << "\t\t" << bt[i] <<"\t "
<< wt[i] <<"\t\t " << tat[i] <<endl;
}

cout << "Average waiting time = "


<< (float)total_wt / (float)n;
cout << "\nAverage turn around time = "
<< (float)total_tat / (float)n;
}

// Driver code
int main()
{
// process id's
int processes[] = { 1, 2, 3};
int n = sizeof processes / sizeof processes[0];

// Burst time of all processes


int burst_time[] = {10, 5, 8};

48 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

// Time quantum
int quantum = 2;
findavgTime(processes, n, burst_time, quantum);
return 0;
}

OUTPUT:
PN BT WT TAT
1 10 13 23
2 5 10 15
3 8 13 21
Average waiting time = 12
Average turn around time = 19.6667

49 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Program 4: Priority Scheduling

// C++ program for implementation of FCFS


// scheduling
#include <bits/stdc++.h>
using namespace std;

struct Process {
int pid; // Process ID
int bt; // CPU Burst time required
int priority; // Priority of this process
};

// Function to sort the Process acc. to priority


bool comparison(Process a, Process b)
{
return ([Link] > [Link]);
}

// Function to find the waiting time for all


// processes
void findWaitingTime(Process proc[], int n, int wt[])
{
// waiting time for first process is 0
wt[0] = 0;

// calculating waiting time


for (int i = 1; i < n; i++)
wt[i] = proc[i - 1].bt + wt[i - 1];
}

50 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

// Function to calculate turn around time


void findTurnAroundTime(Process proc[], int n, int wt[],
int tat[])
{
// calculating turnaround time by adding
// bt[i] + wt[i]
for (int i = 0; i < n; i++)
tat[i] = proc[i].bt + wt[i];
}

// Function to calculate average time


void findavgTime(Process proc[], int n)
{
int wt[n], tat[n], total_wt = 0, total_tat = 0;

// Function to find waiting time of all processes


findWaitingTime(proc, n, wt);

// Function to find turn around time for all processes


findTurnAroundTime(proc, n, wt, tat);

// Display processes along with all details


cout << "\nProcesses "
<< " Burst time "
<< " Waiting time "
<< " Turn around time\n";

// Calculate total waiting time and total turn


// around time
for (int i = 0; i < n; i++) {

51 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

total_wt = total_wt + wt[i];


total_tat = total_tat + tat[i];
cout << " " << proc[i].pid << "\t\t" << proc[i].bt
<< "\t " << wt[i] << "\t\t " << tat[i]
<< endl;
}

cout << "\nAverage waiting time = "


<< (float)total_wt / (float)n;
cout << "\nAverage turn around time = "
<< (float)total_tat / (float)n;
}

void priorityScheduling(Process proc[], int n)


{
// Sort processes by priority
sort(proc, proc + n, comparison);

cout << "Order in which processes gets executed \n";


for (int i = 0; i < n; i++)
cout << proc[i].pid << " ";

findavgTime(proc, n);
}

// Driver code
int main()
{
Process proc[]
= { { 1, 10, 2 }, { 2, 5, 0 }, { 3, 8, 1 } };
int n = sizeof proc / sizeof proc[0];

52 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

priorityScheduling(proc, n);
return 0;
}

OUTPUT:

Order in which processes gets executed


132
Processes Burst time Waiting time Turn around time
1 10 0 10
3 8 10 18
2 5 18 23

Average waiting time = 9.33333


Average turn around time = 17

PYTHON IMPLEMENTATION

print("FIRST COME FIRST SERVE SCHEDULLING")


n= int(input("Enter number of processes : "))
d = dict()

for i in range(n):
key = "P"+str(i+1)
a = int(input("Enter arrival time of process"+str(i+1)+": "))
b = int(input("Enter burst time of process"+str(i+1)+": "))
l = []
[Link](a)
[Link](b)
d[key] = l

d = sorted([Link](), key=lambda item: item[1][0])

ET = []
for i in range(len(d)):
# first process
if(i==0):
[Link](d[i][1][1])

53 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

# get prevET + newBT


else:
[Link](ET[i-1] + d[i][1][1])

TAT = []
for i in range(len(d)):
[Link](ET[i] - d[i][1][0])

WT = []
for i in range(len(d)):
[Link](TAT[i] - d[i][1][1])

avg_WT = 0
for i in WT:
avg_WT +=i
avg_WT = (avg_WT/n)

print("Process | Arrival | Burst | Exit | Turn Around | Wait |")


for i in range(n):
print(" ",d[i][0]," | ",d[i][1][0]," | ",d[i][1][1]," |
",ET[i]," | ",TAT[i]," | ",WT[i]," | ")
print("Average Waiting Time: ",avg_WT)

FIRST COME FIRST SERVE SCHEDULLING

Enter number of processes : 4


Enter arrival time of process1: 1
Enter burst time of process1: 5
Enter arrival time of process2: 0
Enter burst time of process2: 4
Enter arrival time of process3: 3
Enter burst time of process3: 3
Enter arrival time of process4: 2
Enter burst time of process4: 5

Process | Arrival | Burst | Exit | Turn Around | Wait |


P2 | 0 | 4 | 4 | 4 | 0 |
P1 | 1 | 5 | 9 | 8 | 3 |
P4 | 2 | 5 | 14 | 12 | 7 |
P3 | 3 | 3 | 17 | 14 | 11 |
Average Waiting Time: 5.25

54 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

2) SJF- Nonpreemptive
class SJF:

def processData(self, no_of_processes):


process_data = []
for i in range(no_of_processes):
temporary = []
process_id = int(input("Enter Process ID: "))

arrival_time = int(input(f"Enter Arrival Time for Process {process_id}: "))

burst_time = int(input(f"Enter Burst Time for Process {process_id}: "))


[Link]([process_id, arrival_time, burst_time, 0])
'''
'0' is the state of the process. 0 means not executed and 1 means execution complete
'''
process_data.append(temporary)
[Link](self, process_data)

def schedulingProcess(self, process_data):


start_time = []
exit_time = []
s_time = 0
process_data.sort(key=lambda x: x[1])
'''
Sort processes according to the Arrival Time
'''
for i in range(len(process_data)):
ready_queue = []
temp = []

55 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

normal_queue = []

for j in range(len(process_data)):
if (process_data[j][1] <= s_time) and (process_data[j][3] == 0):
[Link]([process_data[j][0], process_data[j][1], process_data[j][2]])
ready_queue.append(temp)
temp = []
elif process_data[j][3] == 0:
[Link]([process_data[j][0], process_data[j][1], process_data[j][2]])
normal_queue.append(temp)
temp = []

if len(ready_queue) != 0:
ready_queue.sort(key=lambda x: x[2])
'''
Sort the processes according to the Burst Time
'''
start_time.append(s_time)
s_time = s_time + ready_queue[0][2]
e_time = s_time
exit_time.append(e_time)
for k in range(len(process_data)):
if process_data[k][0] == ready_queue[0][0]:
break
process_data[k][3] = 1
process_data[k].append(e_time)

elif len(ready_queue) == 0:
if s_time < normal_queue[0][1]:
s_time = normal_queue[0][1]
start_time.append(s_time)

56 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

s_time = s_time + normal_queue[0][2]


e_time = s_time
exit_time.append(e_time)
for k in range(len(process_data)):
if process_data[k][0] == normal_queue[0][0]:
break
process_data[k][3] = 1
process_data[k].append(e_time)

t_time = [Link](self, process_data)


w_time = [Link](self, process_data)
[Link](self, process_data, t_time, w_time)

def calculateTurnaroundTime(self, process_data):


total_turnaround_time = 0
for i in range(len(process_data)):
turnaround_time = process_data[i][4] - process_data[i][1]
'''
turnaround_time = completion_time - arrival_time
'''
total_turnaround_time = total_turnaround_time + turnaround_time
process_data[i].append(turnaround_time)
average_turnaround_time = total_turnaround_time / len(process_data)
'''
average_turnaround_time = total_turnaround_time / no_of_processes
'''
return average_turnaround_time

def calculateWaitingTime(self, process_data):

57 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

total_waiting_time = 0
for i in range(len(process_data)):
waiting_time = process_data[i][5] - process_data[i][2]
'''
waiting_time = turnaround_time - burst_time
'''
total_waiting_time = total_waiting_time + waiting_time
process_data[i].append(waiting_time)
average_waiting_time = total_waiting_time / len(process_data)
'''
average_waiting_time = total_waiting_time / no_of_processes
'''
return average_waiting_time

def printData(self, process_data, average_turnaround_time, average_waiting_time):


process_data.sort(key=lambda x: x[0])
'''
Sort processes according to the Process ID
'''
print("Process_ID Arrival_Time Burst_Time Completed Completion_Time
Turnaround_Time Waiting_Time")

for i in range(len(process_data)):
for j in range(len(process_data[i])):

print(process_data[i][j], end=" ")


print()

print(f'Average Turnaround Time: {average_turnaround_time}')

58 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

print(f'Average Waiting Time: {average_waiting_time}')

if __name__ == "__main__":
no_of_processes = int(input("Enter number of processes: "))
sjf = SJF()
[Link](no_of_processes)

OUTPUT:
Enter number of processes: 5
Enter Process ID: 1
Enter Arrival Time for Process 1: 3
Enter Burst Time for Process 1: 1
Enter Process ID: 2
Enter Arrival Time for Process 2: 1
Enter Burst Time for Process 2: 4
Enter Process ID: 3
Enter Arrival Time for Process 3: 4
Enter Burst Time for Process 3: 2
Enter Process ID: 4
Enter Arrival Time for Process 4: 0
Enter Burst Time for Process 4: 6
Enter Process ID: 5
Enter Arrival Time for Process 5: 2
Enter Burst Time for Process 5: 3

Process ID Arrival Time Burst Time Completed Completion Time Turnaround Time Waiting Time

1 3 1 1 7 4 3

2 1 4 1 16 15 11

3 4 2 1 9 5 3

4 0 6 1 6 6 0

5 2 3 1 12 10 7

Average Turnaround Time: 8.0


Average Waiting Time: 4.8

59 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Python implementation of SRTF

class SJF:

def processData(self, no_of_processes):

process_data = []

for i in range(no_of_processes):

temporary = []

process_id = int(input("Enter Process ID: "))

arrival_time = int(input(f"Enter Arrival Time for Process {process_id}: " ))

burst_time = int(input(f"Enter Burst Time for Process {process_id}: " ))

[Link]([process_id, arrival_time, burst_time, 0, burst_time])

'''

'0' is the state of the process. 0 means not executed and 1 means execution
complete

'''

process_data.append(temporary)

[Link]( self, process_data)

def schedulingProcess (self, process_data):

start_time = []

exit_time = []

s_time = 0

sequence_of_process = []

process_data.sort(key= lambda x: x[1])

'''

Sort processes according to the Arrival Time

'''

while 1:

ready_queue = []

60 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

normal_queue = []

temp = []

for i in range(len(process_data)):

if process_data[i][ 1] <= s_time and process_data[i][ 3] == 0:

[Link]([process_data[i][ 0], process_data[i][ 1], process_data[i]


[2], process_data[i][ 4]])

ready_queue.append(temp)

temp = []

elif process_data[i][ 3] == 0:

[Link]([process_data[i][ 0], process_data[i][ 1], process_data[i]


[2], process_data[i][ 4]])

normal_queue.append(temp)

temp = []

if len(ready_queue) == 0 and len(normal_queue) == 0:

break

if len(ready_queue) != 0:

ready_queue.sort(key= lambda x: x[2])

'''

Sort processes according to Burst Time

'''

start_time.append(s_time)

s_time = s_time + 1

e_time = s_time

exit_time.append(e_time)

sequence_of_process.append(ready_queue[ 0][0])

for k in range(len(process_data)):

if process_data[k][ 0] == ready_queue[ 0][0]:

break

process_data[k][ 2] = process_data[k][ 2] - 1

61 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

if process_data[k][ 2] == 0: #If Burst Time of a process is 0, it means


the process is completed

process_data[k][ 3] = 1

process_data[k].append(e_time)

if len(ready_queue) == 0:

if s_time < normal_queue[0][1]:

s_time = normal_queue[ 0][1]

start_time.append(s_time)

s_time = s_time + 1

e_time = s_time

exit_time.append(e_time)

sequence_of_process.append(normal_queue[ 0][0])

for k in range(len(process_data)):

if process_data[k][ 0] == normal_queue[ 0][0]:

break

process_data[k][ 2] = process_data[k][ 2] - 1

if process_data[k][ 2] == 0: #If Burst Time of a process is 0, it means


the process is completed

process_data[k][ 3] = 1

process_data[k].append(e_time)

t_time = [Link]( self, process_data)

w_time = [Link]( self, process_data)

[Link]( self, process_data, t_time, w_time, sequence_of_process)

def calculateTurnaroundTime (self, process_data):

total_turnaround_time = 0

for i in range(len(process_data)):

turnaround_time = process_data[i][ 5] - process_data[i][1]

'''

turnaround_time = completion_time - arrival_time

62 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

'''

total_turnaround_time = total_turnaround_time + turnaround_time

process_data[i].append(turnaround_time)

average_turnaround_time = total_turnaround_time / len(process_data)

'''

average_turnaround_time = total_turnaround_time / no_of_processes

'''

return average_turnaround_time

def calculateWaitingTime (self, process_data):

total_waiting_time = 0

for i in range(len(process_data)):

waiting_time = process_data[i][ 6] - process_data[i][4]

'''

waiting_time = turnaround_time - burst_time

'''

total_waiting_time = total_waiting_time + waiting_time

process_data[i].append(waiting_time)

average_waiting_time = total_waiting_time / len(process_data)

'''

average_waiting_time = total_waiting_time / no_of_processes

'''

return average_waiting_time

def printData(self, process_data, average_turnaround_time, average_waiting_time,


sequence_of_process):

process_data.sort(key= lambda x: x[0])

'''

Sort processes according to the Process ID

'''

63 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

print("Process_ID Arrival_Time Rem_Burst_Time Completed


Orig_Burst_Time Completion_Time Turnaround_Time Waiting_Time" )

for i in range(len(process_data)):

for j in range(len(process_data[i])):

print(process_data[i][j], end= "\t\t\t\t")

print()

print(f'Average Turnaround Time: {average_turnaround_time}' )

print(f'Average Waiting Time: {average_waiting_time}' )

print(f'Sequence of Process: {sequence_of_process}' )

if __name__ == "__main__":

no_of_processes = int(input("Enter number of processes: " ))

sjf = SJF()

[Link](no_of_processes)

Python implementation of Round Robin


## ROUND ROBIN
class RoundRobin:

def processData(self, no_of_processes):


process_data = []
for i in range(no_of_processes):
temporary = []
process_id = int(input("Enter Process ID: "))

arrival_time = int(input(f"Enter Arrival Time for Process {process_id}: "))

burst_time = int(input(f"Enter Burst Time for Process {process_id}: "))

64 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

[Link]([process_id, arrival_time, burst_time, 0, burst_time])


'''
'0' is the state of the process. 0 means not executed and 1 means execution complete

'''
process_data.append(temporary)

time_slice = int(input("Enter Time Slice: "))

[Link](self, process_data, time_slice)

def schedulingProcess(self, process_data, time_slice):


start_time = []
exit_time = []
executed_process = []
ready_queue = []
s_time = 0
process_data.sort(key=lambda x: x[1])
'''
Sort processes according to the Arrival Time
'''
while 1:
normal_queue = []
temp = []
for i in range(len(process_data)):
if process_data[i][1] <= s_time and process_data[i][3] == 0:
present = 0
if len(ready_queue) != 0:
for k in range(len(ready_queue)):
if process_data[i][0] == ready_queue[k][0]:
present = 1

65 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

'''
The above if loop checks that the next process is not a part of ready_queue
'''
if present == 0:
[Link]([process_data[i][0], process_data[i][1], process_data[i][2],
process_data[i][4]])
ready_queue.append(temp)
temp = []
'''
The above if loop adds a process to the ready_queue only if it is not already
present in it
'''
if len(ready_queue) != 0 and len(executed_process) != 0:
for k in range(len(ready_queue)):
if ready_queue[k][0] == executed_process[len(executed_process) - 1]:
ready_queue.insert((len(ready_queue) - 1), ready_queue.pop(k))
'''
The above if loop makes sure that the recently executed process is appended at
the end of ready_queue
'''
elif process_data[i][3] == 0:
[Link]([process_data[i][0], process_data[i][1], process_data[i][2],
process_data[i][4]])
normal_queue.append(temp)
temp = []
if len(ready_queue) == 0 and len(normal_queue) == 0:
break
if len(ready_queue) != 0:
if ready_queue[0][2] > time_slice:
'''

66 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

If process has remaining burst time greater than the time slice, it will execute
for a time period equal to time slice and then switch
'''
start_time.append(s_time)
s_time = s_time + time_slice
e_time = s_time
exit_time.append(e_time)
executed_process.append(ready_queue[0][0])
for j in range(len(process_data)):
if process_data[j][0] == ready_queue[0][0]:
break
process_data[j][2] = process_data[j][2] - time_slice
ready_queue.pop(0)
elif ready_queue[0][2] <= time_slice:
'''
If a process has a remaining burst time less than or equal to time slice, it will
complete its execution
'''
start_time.append(s_time)
s_time = s_time + ready_queue[0][2]
e_time = s_time
exit_time.append(e_time)
executed_process.append(ready_queue[0][0])
for j in range(len(process_data)):
if process_data[j][0] == ready_queue[0][0]:
break
process_data[j][2] = 0
process_data[j][3] = 1
process_data[j].append(e_time)
ready_queue.pop(0)
elif len(ready_queue) == 0:

67 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

if s_time < normal_queue[0][1]:


s_time = normal_queue[0][1]
if normal_queue[0][2] > time_slice:
'''
If process has remaining burst time greater than the time slice, it will execute
for a time period equal to time slice and then switch
'''
start_time.append(s_time)
s_time = s_time + time_slice
e_time = s_time
exit_time.append(e_time)
executed_process.append(normal_queue[0][0])
for j in range(len(process_data)):
if process_data[j][0] == normal_queue[0][0]:
break
process_data[j][2] = process_data[j][2] - time_slice
elif normal_queue[0][2] <= time_slice:
'''
If a process has a remaining burst time less than or equal to time slice, it will
complete its execution
'''
start_time.append(s_time)
s_time = s_time + normal_queue[0][2]
e_time = s_time
exit_time.append(e_time)
executed_process.append(normal_queue[0][0])
for j in range(len(process_data)):
if process_data[j][0] == normal_queue[0][0]:
break
process_data[j][2] = 0
process_data[j][3] = 1

68 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

process_data[j].append(e_time)
t_time = [Link](self, process_data)
w_time = [Link](self, process_data)
[Link](self, process_data, t_time, w_time, executed_process)

def calculateTurnaroundTime(self, process_data):


total_turnaround_time = 0
for i in range(len(process_data)):
turnaround_time = process_data[i][5] - process_data[i][1]
'''
turnaround_time = completion_time - arrival_time
'''
total_turnaround_time = total_turnaround_time + turnaround_time
process_data[i].append(turnaround_time)
average_turnaround_time = total_turnaround_time / len(process_data)
'''
average_turnaround_time = total_turnaround_time / no_of_processes
'''
return average_turnaround_time

def calculateWaitingTime(self, process_data):


total_waiting_time = 0
for i in range(len(process_data)):
waiting_time = process_data[i][6] - process_data[i][4]
'''
waiting_time = turnaround_time - burst_time
'''
total_waiting_time = total_waiting_time + waiting_time
process_data[i].append(waiting_time)
average_waiting_time = total_waiting_time / len(process_data)
'''

69 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

average_waiting_time = total_waiting_time / no_of_processes


'''
return average_waiting_time

def printData(self, process_data, average_turnaround_time, average_waiting_time,


executed_process):
process_data.sort(key=lambda x: x[0])
'''
Sort processes according to the Process ID
'''
print("Process_ID Arrival_Time Rem_Burst_Time Completed
Original_Burst_Time Completion_Time Turnaround_Time Waiting_Time")
for i in range(len(process_data)):
for j in range(len(process_data[i])):

print(process_data[i][j], end=" ")


print()

print(f'Average Turnaround Time: {average_turnaround_time}')

print(f'Average Waiting Time: {average_waiting_time}')

print(f'Sequence of Processes: {executed_process}')

if __name__ == "__main__":
no_of_processes = int(input("Enter number of processes: "))
rr = RoundRobin()
[Link](no_of_processes)
OUTPUT OF RR:
Enter number of processes: 5
Enter Process ID: 0

70 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Enter Arrival Time for Process 0: 0


Enter Burst Time for Process 0: 5
Enter Process ID: 1
Enter Arrival Time for Process 1: 1
Enter Burst Time for Process 1: 3
Enter Process ID: 2
Enter Arrival Time for Process 2: 2
Enter Burst Time for Process 2: 1
Enter Process ID: 3
Enter Arrival Time for Process 3: 3
Enter Burst Time for Process 3: 2
Enter Process ID: 4
Enter Arrival Time for Process 4: 4
Enter Burst Time for Process 4: 3
Enter Time Slice: 2

PID [Link] Remain._BurstT Completed Ori._Burst_T Completion_T TAT WT


0 0 0 1 5 13 13 8

1 1 0 1 3 12 11 8

2 2 0 1 1 5 3 2

3 3 0 1 2 9 6 4

4 4 0 1 3 14 10 7

Average Turnaround Time: 8.6


Average Waiting Time: 5.8
Sequence of Processes: [0, 1, 2, 0, 3, 4, 1, 0, 4]

Python implementation of Priority Non preemptive

#Priority Non Preemptive


class Priority:

def processData(self, no_of_processes):


process_data = []
for i in range(no_of_processes):

71 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

temporary = []
process_id = int(input("Enter Process ID: "))

arrival_time = int(input(f"Enter Arrival Time for Process {process_id}: "))

burst_time = int(input(f"Enter Burst Time for Process {process_id}: "))

priority = int(input(f"Enter Priority for Process {process_id}: "))

[Link]([process_id, arrival_time, burst_time, priority, 0])


'''
'0' is the state of the process. 0 means not executed and 1 means execution complete
'''
process_data.append(temporary)
[Link](self, process_data)

def schedulingProcess(self, process_data):


start_time = []
exit_time = []
s_time = 0
process_data.sort(key=lambda x: x[1])
'''
Sort processes according to the Arrival Time
'''
for i in range(len(process_data)):
ready_queue = []
temp = []
normal_queue = []
for j in range(len(process_data)):
if (process_data[j][1] <= s_time) and (process_data[j][4] == 0):

72 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

[Link]([process_data[j][0], process_data[j][1], process_data[j][2],


process_data[j][3]])
ready_queue.append(temp)
temp = []
elif process_data[j][4] == 0:
[Link]([process_data[j][0], process_data[j][1], process_data[j][2],
process_data[j][3]])
normal_queue.append(temp)
temp = []
if len(ready_queue) != 0:
ready_queue.sort(key=lambda x: x[3], reverse=True)
'''
Sort the processes according to the Priority, considering Higher the Value, Higher
the Priority
'''
start_time.append(s_time)
s_time = s_time + ready_queue[0][2]
e_time = s_time
exit_time.append(e_time)
for k in range(len(process_data)):
if process_data[k][0] == ready_queue[0][0]:
break
process_data[k][4] = 1
process_data[k].append(e_time)
elif len(ready_queue) == 0:
if s_time < normal_queue[0][1]:
s_time = normal_queue[0][1]
start_time.append(s_time)
s_time = s_time + normal_queue[0][2]
e_time = s_time
exit_time.append(e_time)

73 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

for k in range(len(process_data)):
if process_data[k][0] == normal_queue[0][0]:
break
process_data[k][4] = 1
process_data[k].append(e_time)
t_time = [Link](self, process_data)
w_time = [Link](self, process_data)
[Link](self, process_data, t_time, w_time)

def calculateTurnaroundTime(self, process_data):


total_turnaround_time = 0
for i in range(len(process_data)):
turnaround_time = process_data[i][5] - process_data[i][1]
'''
turnaround_time = completion_time - arrival_time
'''
total_turnaround_time = total_turnaround_time + turnaround_time
process_data[i].append(turnaround_time)
average_turnaround_time = total_turnaround_time / len(process_data)
'''
average_turnaround_time = total_turnaround_time / no_of_processes
'''
return average_turnaround_time

def calculateWaitingTime(self, process_data):


total_waiting_time = 0
for i in range(len(process_data)):
waiting_time = process_data[i][6] - process_data[i][2]
'''

74 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

waiting_time = turnaround_time - burst_time


'''
total_waiting_time = total_waiting_time + waiting_time
process_data[i].append(waiting_time)
average_waiting_time = total_waiting_time / len(process_data)
'''
average_waiting_time = total_waiting_time / no_of_processes
'''
return average_waiting_time

def printData(self, process_data, average_turnaround_time, average_waiting_time):


process_data.sort(key=lambda x: x[0])
'''
Sort processes according to the Process ID
'''
print("Process_ID Arrival_Time Burst_Time Priority Completed
Completion_Time Turnaround_Time Waiting_Time")
for i in range(len(process_data)):
for j in range(len(process_data[i])):
print(process_data[i][j], end="\t\t\t\t")
print()
print(f'Average Turnaround Time: {average_turnaround_time}')

print(f'Average Waiting Time: {average_waiting_time}')

if __name__ == "__main__":
no_of_processes = int(input("Enter number of processes: "))
priority = Priority()
[Link](no_of_processes)

75 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Output of priority Non Preemptive:

76 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Name of the Student: __________________________________Roll no: ___


CLASS: - T.E. [Computer Engineering] Division: B Course: - Lab Practices-I
Assignment-4
Write a program to simulate Page Replacement Algorithm.

Marks: /10
Date of Performance: Sign with Date
/ / 2023

Aim: Write a program to simulate Memory placement strategies – best fit, first fit,
next fit and worst fit..

 Objective .
1. To study page replacement policies to understand memory management.
2. To understand efficient frame management using replacement policies.
 Theory :
 CONCEPT OF PAGE REPLACEMENT:
1. Page Fault: Absence of page when referenced in main memory during paging leads to a page
fault.
2. Page Replacement: Replacement of already existing page from main memory by the required
new page is called as page replacement. And the techniques used for it are called as page replacement
algorithms.

 NEED OF PAGE REPLACEMENT:


Page replacement is used primarily for the virtual memory management because in virtual memory
77 system
paging | Department Computer
principal issue Engineering, SIT, Lonavala
is replacement i.e. which page is to be removed so as to bring in the
new page, thus the use of the page replacement algorithms. Demand paging is the technique used to
increase system throughput. To implement
Downloaded demand(adinaths109@[Link])
by Adinath Sonawane paging page replacement is primary requirement.
lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

 PAGE REPLACEMENT POLICIES:


1. Determine which page to be removed from main memory.
2. Find a free frame.
1) If a frame is found use it
2) if no free frame found, use page replacement algorithm to select a victim frame.
3) Write the victim page to the disk.
3. Read the desired page into the new free frame, change the page and frame tables.
4. Restart the user process.

PAGE REPLACEMENT ALGORITHMS:


1. FIFO
This is the simplest page replacement algorithm. In this algorithm, the operating
system keeps track of all pages in the memory in a queue, the oldest page is in the
front of the queue. When a page needs to be replaced page in the front of the queue is
selected for removal.

2. OPTIMAL PAGE REPLACEMENT ALGORITHM:


Replace the page that will not be used for longest period of time as compared to the
other pages in main memory. An optimal page replacement algorithm has lowest
page fault rate of all algorithm. It is called as OPT or MIN.
ADVANTAGE:
1) This algorithm guarantees the lowest possible page-fault rate for a fixed no. of
frames.
DISADVANTAGE:
1) The optimal page replacement algorithm is very difficult to implement, as it
requires the knowledge of reference strings i.e. strings of memory references.

78 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

3. LEAST RECENTLY USED (LRU):


LRU algorithm uses the time of the page’s last usage. It uses the recent past as an
approximation of the near future, then we can replace the page that has not been used
for the longest period of the time i.e. the page having larger idle time is replaced.
ADVANTAGE:
1) The LRU policy is often used for page replacement and is considered to be good.
DISADVANTAGES:
1) It is very difficult to implement.
2) Requires substantial hardware assistance.
3) The problematic determination of the order for the frames defined by the time of
last usage.

 Algorithm/Flowchart:
1. FIFO :
1. Start the process
2. Read number of pages n
3. Read number of pages no
4. Read page numbers into an array a[i]
5. Initialize avail[i]=0 .to check page hit
6. Replace the page with circular queue, while re-placing check page availability
in the frame Place avail[i]=1 if page is placed in the frame Count page faults
7. Print the results.
8. Stop the process.

2. LEAST RECENTLY USED


[Link] the process
2. Declare the size
3. Get the number of pages to be inserted

79 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

4. Get the value


5. Declare counter and stack
6. Select the least recently used page by counter value
7. Stack them according the selection.
8. Display the values
9. Stop the process

3. OPTIMAL ALGORTHIM:
1. Start Program
2. Read Number Of Pages And Frames
[Link] Each Page Value
4. Search For Page In The Frames
5. If Not Available Allocate Free Frame
6. If No Frames Is Free Replace The Page With The Page That Is Least Used
7. Print Page Number Of Page Faults
8. Stop process.

Conclusion:
Successfully implemented all page replacement policies.

80 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Program for page replacement algorithm


1) FIFO
#FIFO page replacement algorithm implementation in python

print("Enter the number of frames: ",end="")


capacity = int(input())
f,fault,top,pf = [],0,0,'No'
print("Enter the reference string: ",end="")
s = list(map(int,input().strip().split()))
print("\nString|Frame →\t",end='')
for i in range(capacity):
print(i,end=' ')
print("Fault\n ↓\n")
for i in s:
if i not in f:
if len(f)<capacity:
[Link](i)
else:
f[top] = i
top = (top+1)%capacity
fault += 1
pf = 'Yes'
else:
pf = 'No'
print(" %d\t\t"%i,end='')
for x in f:
print(x,end=' ')
for x in range(capacity-len(f)):
print(' ',end=' ')
print(" %s"%pf)
print("\nTotal requests: %d\nTotal Page Faults: %d\nFault Rate:
%0.2f%%"%(len(s),fault,(fault/len(s))*100))

output:
Enter the number of frames: 3
Enter the reference string: 1 2 3 4 1 6 7 8 2

81 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

String|Frame → 0 1 2 Fault

1 1 Yes
2 1 2 Yes
3 1 2 3 Yes
4 4 2 3 Yes
1 4 1 3 Yes
6 4 1 6 Yes
7 7 1 6 Yes
8 7 8 6 Yes
2 7 8 2 Yes

Total requests: 9
Total Page Faults: 9
Fault Rate: 100.00%

2) LRU

#LRU page replacement algorithm implementation in python

print("Enter the number of frames: ",end="")


capacity = int(input())
f,st,fault,pf = [],[],0,'No'
print("Enter the reference string: ",end="")
s = list(map(int,input().strip().split()))
print("\nString|Frame →\t",end='')
for i in range(capacity):
print(i,end=' ')
print("Fault\n ↓\n")
for i in s:
if i not in f:
if len(f)<capacity:
[Link](i)

82 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

[Link](len(f)-1)
else:
ind = [Link](0)
f[ind] = i
[Link](ind)
pf = 'Yes'
fault += 1
else:
[Link]([Link]([Link]([Link](i))))
pf = 'No'
print(" %d\t\t"%i,end='')
for x in f:
print(x,end=' ')
for x in range(capacity-len(f)):
print(' ',end=' ')
print(" %s"%pf)
print("\nTotal Requests: %d\nTotal Page Faults: %d\nFault Rate:
%0.2f%%"%(len(s),fault,(fault/len(s))*100))

OUTPUT:
Enter the number of frames: 3
Enter the reference string: 1 2 3 4 1 6 7 8 2

String|Frame → 0 1 2 Fault

1 1 Yes
2 1 2 Yes
3 1 2 3 Yes
4 4 2 3 Yes
1 4 1 3 Yes
6 4 1 6 Yes
7 7 1 6 Yes
8 7 8 6 Yes
2 7 8 2 Yes

Total Requests: 9
Total Page Faults: 9
Fault Rate: 100.00%

3) OPTIMAL

83 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

#Optimal page replacement algorithm (OPT or OPR) implementation in


python

print("Enter the number of frames: ",end="")


capacity = int(input())
f,fault,pf = [],0,'No'
print("Enter the reference string: ",end="")
s = list(map(int,input().strip().split()))
print("\nString|Frame →\t",end='')
for i in range(capacity):
print(i,end=' ')
print("Fault\n ↓\n")
occurance = [None for i in range(capacity)]
for i in range(len(s)):
if s[i] not in f:
if len(f)<capacity:
[Link](s[i])
else:
for x in range(len(f)):
if f[x] not in s[i+1:]:
f[x] = s[i]
break
else:
occurance[x] = s[i+1:].index(f[x])
else:
f[[Link](max(occurance))] = s[i]
fault += 1
pf = 'Yes'
else:
pf = 'No'
print(" %d\t\t"%s[i],end='')
for x in f:
print(x,end=' ')
for x in range(capacity-len(f)):
print(' ',end=' ')
print(" %s"%pf)

84 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

print("\nTotal requests: %d\nTotal Page Faults: %d\nFault Rate:


%0.2f%%"%(len(s),fault,(fault/len(s))*100))

output:

Enter the number of frames: 3


Enter the reference string: 1 2 3 4 1 6 7 8 2

String|Frame → 0 1 2 Fault

1 1 Yes
2 1 2 Yes
3 1 2 3 Yes
4 1 2 4 Yes
1 1 2 4 No
6 6 2 4 Yes
7 7 2 4 Yes
8 8 2 4 Yes
2 8 2 4 No

Total requests: 9
Total Page Faults: 7
Fault Rate: 77.78%

85 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Name of the Student: __________________________________Roll no: ___


CLASS: - T.E. [Computer Engineering] Division: C Course: - Lab Practices-I
Assignment-5
Write a program to simulate Memory placement strategies – best fit, first fit, next fit and worst fit.

Marks: /10
Date of Performance: Sign with Date
/ / 2023

Aim: Write a program to simulate Memory placement strategies – best fit, first fit,
next fit and worst fit..

 Objective .
1. To study Memory Placement strategies to understand memory management.
2.
 Theory :
 CONCEPT OF MEMORY PLACEMENT STRATEGIES:
In the operating system, the following are four common memory management
techniques.

[Link] contiguous allocation: Simplest allocation method used by MS-DOS. All memory
(except some reserved for OS) is available to a process.

[Link] allocation: Memory is divided into different blocks or partitions. Each


process is allocated according to the requirement.

86 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

[Link] memory management:


Memory is divided into fixed-sized units called page frames, used in a virtual memory
environment.
[Link] memory management:
Memory is divided into different segments (a segment is a logical grouping of the
process’ data or code).In this management, allocated memory doesn’t have to be
contiguous.

Most of the operating systems (for example Windows and Linux) use Segmentation with
Paging. A process is divided into segments and individual segments have pages.

In Partition Allocation, when there is more than one partition freely available to
accommodate a process’s request, a partition must be selected. To choose a particular
partition, a partition allocation method is needed. A partition allocation method is
considered better if it avoids internal fragmentation.

When it is time to load a process into the main memory and if there is more than one free
block of memory of sufficient size then the OS decides which free block to allocate.

There are different Placement Algorithm:

A. First Fit

B. Best Fit

C. Worst Fit

D. Next Fit

87 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

A. FIRST FIT ALLOCATION:


The First Fit memory allocation checks the empty memory blocks in a sequential manner. It
means that the memory Block which found empty in the first attempt is checked for size.
But if the size is not less than the required size then it is allocated.

Advantage:

It is the fastest searching Algorithm as we not to search only first block, we do not need to search
a lot.

Disadvantage:

The main disadvantage of First Fit is that the extra space cannot be used by any other
[Link] the memory is allocated it creates large amount of chunks of memory space.

First Fit Memory Management Scheme:


In the First Fit Memory Management Scheme, we check the block in the sequential manner i.e
we take the first process and compare its size with the first block.

If the size is less than the size of the first block then only it is allocated. Otherwise, we move to
the second block and this process is continuously going on until all processes are allocated.

Algorithm of First Fit:


1 Step: START.
2 Step: At first get the no of processes and blocks.
3 Step: Allocate the process by if(size of block>=size of the process) then allocate the process
else move to the next block.
4 Step: Now Display the processes with blocks and allocate to respective process.
5 Step: STOP.

88 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

B. BEST FIT ALLOCATION

This method keeps the free/busy list in order by size – smallest to largest.
In this method, the operating system first searches the whole of the memory according to the size
of the given job and allocates it to the closest-fitting free partition in the memory, making it able
to use memory efficiently. Here the jobs are in the order from smallest job to largest job.

Best-fit allocation is a memory allocation algorithm used in operating systems to allocate


memory to processes. In this algorithm, the operating system searches for the smallest free block
of memory that is big enough to accommodate the process being allocated memory.
The operating system maintains a list of all free memory blocks available in the system.

89 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

When a process requests memory, the operating system searches the list for the smallest free
block of memory that is large enough to accommodate the process.
If a suitable block is found, the process is allocated memory from that block.
If no suitable block is found, the operating system can either wait until a suitable block becomes
available or request additional memory from the system.
The best-fit allocation algorithm has the advantage of minimizing external fragmentation, as it
searches for the smallest free block of memory that can accommodate a process. However, it can
also lead to more internal fragmentation, as processes may not use the entire memory block
allocated to them.
Overall, the best-fit allocation algorithm can be an effective way to allocate memory in an
operating system, but it is important to balance the advantages and disadvantages of this
approach with other allocation algorithms such as first-fit, next-fit, and worst-fit.
Advantages of Best-Fit Allocation :
Memory Efficient.
 The operating system allocates the job minimum possible space in the memory,
making memory management very efficient.
 To save memory from getting wasted, it is the best method.
 Improved memory utilization
 Reduced memory fragmentation
 Minimizes external fragmentation

90 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Disadvantages of Best-Fit Allocation:


 It is a Slow Process. Checking the whole memory for each job makes the working of
the operating system very slow. It takes a lot of time to complete the work.
 Increased computational overhead
 May lead to increased internal fragmentation
 Can result in slow memory allocation times.

C. WORST FIT ALLOCATION

In this allocation technique, the process traverses the whole memory and always search for the
largest hole/partition, and then the process is placed in that hole/partition. It is a slow process
because it has to traverse the entire memory to search the largest hole.

Here is an example to understand Worst Fit-Allocation –

91 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Here Process P1=30K is allocated with the Worst Fit-Allocation technique, so it traverses the
entire memory and selects memory size 400K which is the largest, and hence there is an internal
fragmentation of 370K which is very large and so many other processes can also utilize this
leftover space.

Advantages of Worst-Fit Allocation :


Since this process chooses the largest hole/partition, therefore there will be large internal
fragmentation. Now, this internal fragmentation will be quite big so that other small processes
can also be placed in that leftover partition.

Disadvantages of Worst-Fit Allocation :


It is a slow process because it traverses all the partitions in the memory and then selects the
largest partition among all the partitions, which is a time-consuming process

92 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

[Link] FIT ALLOCATION

The next fit is a modified version of ‘first fit’. It begins as the first fit to find a free partition but
when called next time it starts searching from where it left off, not from the beginning. This
policy makes use of a roving pointer. The pointer moves along the memory chain to search for
the next fit. This helps in, to avoid the usage of memory always from the head (beginning) of the
free blockchain.

Advantage over first fit


First fit is a straight and fast algorithm, but tends to cut a large portion of free parts into small
pieces due to which, processes that need a large portion of memory block would not get anything

93 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

even if the sum of all small pieces is greater than it required which is so-called external
fragmentation problem.
Another problem of the first fit is that it tends to allocate memory parts at the beginning of the
memory, which may lead to more internal fragments at the beginning. Next fit tries to address
this problem by starting the search for the free portion of parts not from the start of the memory,
but from where it ends last time.
Next fit is a very fast searching algorithm and is also comparatively faster than First Fit and Best
Fit Memory Management Algorithms.
Example:
Input : blockSize[] = {5, 10, 20};
processSize[] = {10, 20, 30};
Output:
Process No. Process Size Block no.
1 10 2
2 20 3
3 30 Not Allocated

Algorithm:

 Input the number of memory blocks and their sizes and initializes all the blocks as free.
 Input the number of processes and their sizes.
 Start by picking each process and check if it can be assigned to the current block, if yes,
allocate the required memory and check for next process but from the block where we
left not from starting.
 If the current block size is smaller then keep checking the further blocks.

94 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

95 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Program for First fit


// C++ program for the implementation
// of the First Fit algorithm
#include <iostream>
#include <queue>
#include <vector>
using namespace std;

// Process Class
class process {
public:
// Size & number of process
size_t size;
pid_t no;
};

// Memory Class
class memory {
public:
size_t size;

// Number of memory & queue of space


// occupied by process
pid_t no;
queue<process> space_occupied;

// Function to push process in a block


void push(const process p)
{
if ([Link] <= size) {
space_occupied.push(p);
size -= [Link];
}
}

96 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

// Function to pop and return the


// process from the block
process pop()
{
process p;

// If space occupied is empty


if (!space_occupied.empty()) {
p = space_occupied.front();
space_occupied.pop();
size += [Link];
return p;
}
}

// Function to check if block is


// completely empty
bool empty()
{
return space_occupied.empty();
}
};

// Function to get data of processess


// allocated using first fit
vector<memory> first_fit(vector<memory> memory_blocks,
queue<process> processess)
{
int i = 0;
bool done, done1;
memory na;
[Link] = -10;
while (![Link]()) {
done = 0;
for (i = 0; i < memory_blocks.size(); i++) {

97 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

done1 = 0;
if (memory_blocks.at(i).size
>= [Link]().size) {
memory_blocks.at(i).push([Link]());
done = 1;
done1 = 1;
break;
}
}

// If process is done
if (done == 0 && done1 == 0) {
[Link] += [Link]().size;
[Link]([Link]());
}

// pop the process


[Link]();
}
if (!na.space_occupied.empty())
memory_blocks.push_back(na);
return memory_blocks;
}

// Function to display the allocation


// of all processess
void display(vector<memory> memory_blocks)
{
int i = 0, temp = 0;
process p;
cout << "+-------------+--------------+--------------+"
<< endl;
cout << "| Process no. | Process size | Memory block |"
<< endl;
cout << "+-------------+--------------+--------------+"
<< endl;

98 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

// Traverse memory blocks size


for (i = 0; i < memory_blocks.size(); i++) {

// While memory block size is not empty


while (!memory_blocks.at(i).empty()) {
p = memory_blocks.at(i).pop();
temp = to_string([Link]).length();
cout << "|" << string(7 - temp / 2 - temp % 2, ' ')
<< [Link] << string(6 - temp / 2, ' ')
<< "|";

temp = to_string([Link]).length();
cout << string(7 - temp / 2 - temp % 2, ' ')
<< [Link]
<< string(7 - temp / 2, ' ') << "|";

temp = to_string(memory_blocks.at(i).no).length();
cout << string(7 - temp / 2 - temp % 2, ' ');

// If memory blocks is assigned


if (memory_blocks.at(i).no != -10) {
cout << memory_blocks.at(i).no;
}

// Else memory blocks is assigned


else {
cout << "N/A";
}
cout << string(7 - temp / 2, ' ')
<< "|" << endl;
}
}
cout << "+-------------+--------------+--------------+"
<< endl;
}

99 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

// Driver Code
int main()
{
// Declare memory blocks
vector<memory> memory_blocks(5);

// Declare first fit blocks


vector<memory> first_fit_blocks;

// Declare queue of all processess


queue<process> processess;
process temp;

// Set sample data


memory_blocks[0].no = 1;
memory_blocks[0].size = 400;

memory_blocks[1].no = 2;
memory_blocks[1].size = 500;

memory_blocks[2].no = 3;
memory_blocks[2].size = 300;

memory_blocks[3].no = 4;
memory_blocks[3].size = 200;

memory_blocks[4].no = 5;
memory_blocks[4].size = 100;

[Link] = 1;
[Link] = 88;

// Push the process


[Link](temp);

100 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

[Link] = 2;
[Link] = 192;

// Push the process


[Link](temp);

[Link] = 3;
[Link] = 277;

// Push the process


[Link](temp);

[Link] = 4;
[Link] = 365;

// Push the process


[Link](temp);

[Link] = 5;
[Link] = 489;

// Push the process


[Link](temp);

// Get the data


first_fit_blocks = first_fit(memory_blocks, processess);

// Display the data


display(first_fit_blocks);
memory_blocks.clear();
memory_blocks.shrink_to_fit();
first_fit_blocks.clear();
first_fit_blocks.shrink_to_fit();
return 0;
}

101 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

-------------+--------------+--------------+
| Process no. | Process size | Memory block |
+-------------+--------------+--------------+
| 1 | 88 | 1 |
| 2 | 192 | 1 |
| 3 | 277 | 2 |
| 4 | 365 | N/A |
| 5 | 489 | N/A |
+-------------+--------------+--------------+

2)Program for Next fit

102 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Program: Best Fit Memory Management

// C++ implementation of Best - Fit algorithm


#include<iostream>
using namespace std;

// Method to allocate memory to blocks as per Best fit algorithm


void bestFit(int blockSize[], int m, int processSize[], int n)
{
// Stores block id of the block allocated to a process
int allocation[n];

// Initially no block is assigned to any process


for (int i = 0; i < n; i++)
allocation[i] = -1;

// pick each process and find suitable blocks


// according to its size ad assign to it
for (int i = 0; i < n; i++)
{
// Find the best fit block for current process
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 we could find a block for current process


if (bestIdx != -1)
{
// allocate block j to p[i] process
allocation[i] = bestIdx;

// Reduce available memory in this block.


blockSize[bestIdx] -= processSize[i];
}
}

cout << "\nProcess No.\tProcess Size\tBlock no.\n";


for (int i = 0; i < n; i++)
{
cout << " " << i+1 << "\t\t" << processSize[i] << "\t\t";
if (allocation[i] != -1)
cout << allocation[i] + 1;
else
cout << "Not Allocated";

103 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

cout << endl;


}
}

// Driver Method
int main()
{
int blockSize[] = {100, 500, 200, 300, 600};
int processSize[] = {212, 417, 112, 426};
int m = sizeof(blockSize) / sizeof(blockSize[0]);
int n = sizeof(processSize) / sizeof(processSize[0]);

bestFit(blockSize, m, processSize, n);

return 0 ;
}

OUTPUT:

Process No. Process Size Block no.


1 212 4
2 417 2
3 112 3
4 426 5

104 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Program: Next Fit Memory Management

// C/C++ program for next fit


// memory management algorithm
#include <bits/stdc++.h>
using namespace std;

// Function to allocate memory to blocks as per Next fit


// algorithm
void NextFit(int blockSize[], int m, int processSize[], int n)
{
// Stores block id of the block allocated to a
// process
int allocation[n], j = 0, t = m - 1;

// Initially no block is assigned to any process


memset(allocation, -1, sizeof(allocation));

// pick each process and find suitable blocks


// according to its size ad assign to it
for(int i = 0; i < n; i++){

// Do not start from beginning


while (j < m){
if(blockSize[j] >= processSize[i]){

// allocate block j to p[i] process


allocation[i] = j;

// Reduce available memory in this block.


blockSize[j] -= processSize[i];

// sets a new end point


t = (j - 1) % m;
break;
}
if (t == j){
// sets a new end point
t = (j - 1) % m;
// breaks the loop after going through all memory
block
break;
}

// mod m will help in traversing the


// blocks from starting block after
// we reach the end.
j = (j + 1) % m;
}
}

cout << "\nProcess No.\tProcess Size\tBlock no.\n";


for (int i = 0; i < n; i++) {
cout << " " << i + 1 << "\t\t\t\t" << processSize[i]

105 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

<< "\t\t\t\t";
if (allocation[i] != -1)
cout << allocation[i] + 1;
else
cout << "Not Allocated";
cout << endl;
}
}

// Driver program
int main()
{
int blockSize[] = { 5, 10, 20 };
int processSize[] = { 10, 20, 5 };
int m = sizeof(blockSize) / sizeof(blockSize[0]);
int n = sizeof(processSize) / sizeof(processSize[0]);

NextFit(blockSize, m, processSize, n);

return 0;
}

OUTPUT:
Process No. Process Size Block no.
1 10 2
2 20 3
3 5 1

// C++ implementation of worst - Fit algorithm

106 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

#include<bits/stdc++.h>
using namespace std;

// Function to allocate memory to blocks as per worst fit


// algorithm
void worstFit(int blockSize[], int m, int processSize[],
int
n)
{
// Stores block id of the block allocated to a
// process
int allocation[n];

// Initially no block is assigned to any process


memset(allocation, -1, sizeof(allocation));

// pick each process and find suitable blocks


// according to its size ad assign to it
for (int i=0; i<n; i++)
{
// Find the best fit block for current process
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 we could find a block for current process


if (wstIdx != -1)
{
// allocate block j to p[i] process
allocation[i] = wstIdx;

// Reduce available memory in this block.


blockSize[wstIdx] -= processSize[i];
}
}

cout << "\nProcess No.\tProcess Size\tBlock no.\n";


for (int i = 0; i < n; i++)
{
cout << " " << i+1 << "\t\t" << processSize[i] << "\t\t";
if (allocation[i] != -1)
cout << allocation[i] + 1;
else
cout << "Not Allocated";
cout << endl;
}

107 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

// Driver code
int main()
{
int blockSize[] = {100, 500, 200, 300, 600};
int processSize[] = {212, 417, 112, 426};
int m = sizeof(blockSize)/sizeof(blockSize[0]);
int n = sizeof(processSize)/sizeof(processSize[0]);

worstFit(blockSize, m, processSize, n);

return 0 ;
}

OUTPUT:
Process No. Process Size Block no.
1 212 5
2 417 2
3 112 5
4 426 Not Allocated

Python implementation

1) First fit

# Python3 implementation of First-Fit algorithm

# Function to allocate memory to


# blocks as per First fit algorithm
def firstFit(blockSize, m, processSize, n):

# Stores block id of the


# block allocated to a process
allocation = [-1] * n

# Initially no block is assigned to any process

# pick each process and find suitable blocks


# according to its size ad assign to it
for i in range(n):
for j in range(m):

108 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

if blockSize[j] >= processSize[i]:

# allocate block j to p[i] process


allocation[i] = j

# Reduce available memory in this block.


blockSize[j] -= processSize[i]

break

print(" Process No. Process Size Block no.")


for i in range(n):
print(" ", i + 1, " ", processSize[i],
" ", end = " ")
if allocation[i] != -1:
print(allocation[i] + 1)
else:
print("Not Allocated")

# Driver code
if __name__ == '__main__':
blockSize = [100, 500, 200, 300, 600]
processSize = [212, 417, 112, 426]
m = len(blockSize)
n = len(processSize)

firstFit(blockSize, m, processSize, n)

Output :

Process No. Process Size Block no.


1 212 2
2 417 5
3 112 2
4 426 Not Allocated

2) Next Fit

109 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

# Python3 program for next fit


# memory management algorithm

# Function to allocate memory to


# blocks as per Next fit algorithm
def NextFit(blockSize, m, processSize, n):

# Stores block id of the block


# allocated to a process

# Initially no block is assigned


# to any process
allocation = [-1] * n
j = 0
t = m-1
# pick each process and find suitable blocks
# according to its size ad assign to it
for i in range(n):

# Do not start from beginning


while j < m:
if blockSize[j] >= processSize[i]:

# allocate block j to p[i] process


allocation[i] = j

# Reduce available memory in this block.


blockSize[j] -= processSize[i]

# sets a new end point


t = (j - 1) % m
break
if t == j:
# sets a new end point
t = (j - 1) % m
# breaks the loop after going through all
memory block
break

# mod m will help in traversing the


# blocks from starting block after
# we reach the end.
j = (j + 1) % m

print("Process No. Process Size Block no.")

for i in range(n):
print("\t", i + 1, "\t\t\t", processSize[i],end = "\t\t\
t")
if allocation[i] != -1:
print(allocation[i] + 1)
else:
print("Not Allocated")

110 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

# Driver Code
if __name__ == '__main__':
blockSize = [5, 10, 20]
processSize = [10, 20, 5]
m = len(blockSize)
n = len(processSize)

NextFit(blockSize, m, processSize, n)

Output of Next Fit:


Output
Process No. Process Size Block no.
1 10 2
2 20 3
3 5 1

3) Best Fit

111 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

# Python3 implementation of Best - Fit algorithm

# Function to allocate memory to blocks


# as per Best fit algorithm
def bestFit(blockSize, m, processSize, n):

# Stores block id of the block


# allocated to a process
allocation = [-1] * n

# pick each process and find suitable


# blocks according to its size ad
# assign to it
for i in range(n):

# Find the best fit block for


# current process
bestIdx = -1
for j in range(m):
if blockSize[j] >= processSize[i]:
if bestIdx == -1:
bestIdx = j
elif blockSize[bestIdx] > blockSize[j]:
bestIdx = j

# If we could find a block for


# current process
if bestIdx != -1:

# allocate block j to p[i] process


allocation[i] = bestIdx

# Reduce available memory in this block.


blockSize[bestIdx] -= processSize[i]

print("Process No. Process Size Block no.")


for i in range(n):
print(i + 1, " ", processSize[i],
end = " ")
if allocation[i] != -1:
print(allocation[i] + 1)
else:
print("Not Allocated")

# Driver code
if __name__ == '__main__':
blockSize = [100, 500, 200, 300, 600]
processSize = [212, 417, 112, 426]
m = len(blockSize)
n = len(processSize)

112 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

bestFit(blockSize, m, processSize, n)

Output of best fit

Process No. Process Size Block no.


1 212 4
2 417 2
3 112 3
4 426 5

4) Worst fit

113 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

# Python3 implementation of worst - Fit algorithm

# Function to allocate memory to blocks as


# per worst fit algorithm
def worstFit(blockSize, m, processSize, n):

# Stores block id of the block


# allocated to a process

# Initially no block is assigned


# to any process
allocation = [-1] * n

# pick each process and find suitable blocks


# according to its size ad assign to it
for i in range(n):

# Find the best fit block for


# current process
wstIdx = -1
for j in range(m):
if blockSize[j] >= processSize[i]:
if wstIdx == -1:
wstIdx = j
elif blockSize[wstIdx] < blockSize[j]:
wstIdx = j

# If we could find a block for


# current process
if wstIdx != -1:

# allocate block j to p[i] process


allocation[i] = wstIdx

# Reduce available memory in this block.


blockSize[wstIdx] -= processSize[i]

print("Process No. Process Size Block no.")


for i in range(n):
print(i + 1, " ",
processSize[i], end = " ")
if allocation[i] != -1:
print(allocation[i] + 1)
else:
print("Not Allocated")

# Driver code
if __name__ == '__main__':
blockSize = [100, 500, 200, 300, 600]
processSize = [212, 417, 112, 426]
m = len(blockSize)

114 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

n = len(processSize)

worstFit(blockSize, m, processSize, n)

Output of worst fit :


Process No. Process Size Block no.
1 212 5
2 417 2
3 112 5
4 426 Not Allocated

Name of the Student: ______________________________________ Roll no: ___


CLASS: - T.E. [Computer Engineering] Division: Course: - Lab Practices-I
Assignment-5
Design a user interface in Python

Date of Performance: Sign with Date


Marks: /10

/23

Aim- Design a user interface in Python

Objective:-
To design a user interface in Python

To learn simplicity, user centric approach of a GUI in designing

115 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Learning Outcomes:

A simple GUI designed using Tkinter library in Python.

Requirements:

Tkinter - standard GUI library for Python

Implementa琀椀on Steps:
import the Python GUI Tkinter module:
>>> import tkinter as tk
A window is an instance of Tkinter’s Tk class. Go ahead and create a new window
and assign into the variable window:

>>> window = [Link]()

When you execute the above code, a new window pops up on your screen. How it
looks depends on your opera琀椀ng system:

116 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Adding a Widget Use the [Link] class to add some

text to a window.
Create a Label widget with the text "Hello,Tkinter" and assign it to a variable called gree琀椀ng:

>>>
>>> greeting = [Link] el(text="Hello, Tkinter")
Working With Widgets
Each widget in Tkinter is de昀椀ned by a class. Here are some of the widgets available:

Widget Class Descrip琀椀on


Label A widget used to display text on the screen
Bu琀琀on A bu琀琀on that can contain text and can perform an ac琀椀on when clicked
Entry A text entry widget that allows only a single line of text
Text A text entry widget that allows mul琀椀line text entry
Frame A rectangular region used to group related widgets or provide padding between wid

Displaying Text and Images With Label Widgets

Label widgets are used to display text or images. The text displayed by a Label widget can’t
be edited by the user. It’s for display purposes only. As you saw in the example at the
beginning of this tutorial, you can create a Label widget by instan琀椀a琀椀ng the Label class and
passing a string to the text parameter:

label = [Link](text="Hello, Tkinter")


abel widgets display text with the default system text color and the default system text
background color. These are typically black and white, respec琀椀vely, but you may see
di昀昀erent colors if you have changed these se琀�ngs in your opera琀椀ng system.

You can control Label text and background colors


using the foreground and background parameters:

label = [Link](
text="Hello,
Tkinter",
foreground="white", # Set the text color to white
background="black" # Set the background color to
black

117 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

)
ou can also control the width and height of a label with the width and height parameters:

label = [Link](
text="Hello,
Tkinter",
fg="white",
bg="black",
width=10,
height=10
Here’s what this label looks like in a window:

Displaying Clickable Bu琀琀ons With Bu琀琀on

Widgets bu琀琀on = [Link]琀琀on(


text="Click
me!",
width=25,
height=5,
bg="blue",
fg="yellow",
)

118 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Ge琀�ng User Input With Entry Widgets

he following code creates a widget with a blue background, some yellow text, and a width of 50
text units:

entry = [Link](fg="yellow", bg="blue", width=50)


The best way to get an understanding of Entry widgets is to create one and interact with it.
Open up a Python shell and follow along with the examples in this sec琀椀on. First, import
tkinter and create a new window:

>>> import tkinter as tk


>>> window = [Link]()
Now create a Label and an Entry widget:

>>> label = [Link](text="Name")


>>> entry = [Link]()
The Label describes what sort of text should go in the Entry widget. It doesn’t enforce any sort
of requirements on the Entry, but it tells the user what your program expects them to put
there. You need to .pack() the widgets into the window so that they’re visible:

>>> [Link]()
>>> [Link]()
Here’s what that looks like:

Conclusion: GUI created using Python

119 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Name of the Student: ______________________________________ Roll no: ___


CLASS: - T.E. [Computer Engineering] Division: Course: - Lab Practices-I
Assignment-6
To Redesign existing Graphical User Interface with screen complexity

Ai Marks: /10
Date of Performance: Sign with Date
/23

120 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Aim: To Redesign exis琀椀ng Graphical User Interface with screen complexity

Objec琀椀ve:

 To study principles of Good screen design


 To apply the screen complexity rules to a GUI to improvise it.
 To analyse the human considerations in Interface and screen design

Learning Outcomes:

 Design better screens in interfaces based on visually pleasing structure


 Learn to organize the elements on an interface screen by properly calculating
 the screen complexity.
 Learning the factors that affect the screen design quality with respect to
 user expectations

Requirements:
Any GUI screen from a selected applica琀椀on.
General structure of the elements on the screen to measure complexity factors.

121 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

To calculate the complexity 昀椀rst determine the following:


(1) the number of elements on the screen
(2) the number of horizontal (column) alignment points
(3) the number of ver琀椀cal (row) alignment points

An example is given below:

122 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Original Design of the GUI

 In the above screen the elements are not placed in a proper symmetry, which
creates user confusion and loss of interest in the interface.
 The 昀椀rst requirement is to iden琀椀fy the text boxes and their places on the screen and
then place them in a proper order , also group them as per requirement.
 The re-designed screen for the above example is shown in the 昀椀gure below.
 To validate the improved screen, complexity of the screen is calculated which shows
the op琀椀miza琀椀on of screen space as well as the user friendly interface.

123 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Re-designed Screen design

Calcula琀椀on of complexity:
Original Design
1. 22 elements
2. 6 horizontal (column) alignment points
3. 20 ver琀椀cal (row) alignment points
4. 48 = complexity (addi琀椀on of all counts))
Redesigned Screen
1. 18 elements
2. 7 horizontal (column) alignment points
3. 8 ver琀椀cal (row) alignment points
4. 33 = complexity

Students have to choose an applica琀椀on like the above GUI and calculate the screen complexity
and re-design it by re-arranging the elements on the screen

124 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])


lOMoARcPSD|58943265

T.E. (Computer) Sinhgad Institute of Technology, Lonavala Lab Practices-I

Conclusion:
Brief descrip琀椀on of the studied method for improving screen design complexity and the
improvement in design by applying this method.

125 | Department Computer Engineering, SIT, Lonavala

Downloaded by Adinath Sonawane (adinaths109@[Link])

You might also like