18CSL66 - SS Lab Manual
18CSL66 - SS Lab Manual
18CSL66 - SS Lab Manual
LABORATORY MANUAL
SEMESTER: VI
Vision
Mission
"BIET contributes to the growth and development of its students by imparting a broad based
engineering education and empowering them to be successful in their chosen field by inculcating in
them positive approach, leadership qualities and ethical values"
M2 Creating collaborative learning environment that ignites the critical thinking in students
and leading to the innovation.
M3 Establishing Industry Institute relationship to bridge the skill gap and make them industry
ready and relevant.
∙ PO2. Problem analysis: Identify, formulate, review research literature, and analyze
complex engineering problems reaching substantiated conclusions using first principles
of mathematics, natural sciences, and engineering sciences.
∙ 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
∙ PO8. Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the 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.
∙ PO12. Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.
1. PSO1: Analyze and develop solutions for problems that are complex in nature but
applying the knowledge acquired from the core subjects of this program.. 2. PSO2:
To develop secure, Scalable, Resilient and distributed applications for industry and
societal requirements.
3. PSO3: To learn and apply the concepts and construct of emerging technologies like
Artificial Intelligence, Machine learning, Deep learning, Big Data Analytics, IOT,
Cloud Computing, etc for any real time problems.
PEO1: To apply skills acquired in the discipline of Computer Science and Engineering for
PEO2:
solving societal and industrial problems with apt technology intervention To continue
their career in industry/academia or to pursue higher studies and research. PEO3: To become
successful entrepreneurs, innovators to design and develop software products and services that
meet the societal, technical and business challenges.
Lab Experiments:
1.
a) Write a LEX program to recognize valid arithmetic expression. Identifiers in
the expression could be only integers and operators could be + and *. Count
the identifiers & operators present and print them separately.
NIL
Course outcomes: The students should be able to:
∙ Implement and demonstrate Lexer’s and Parser’s
∙ Evaluate different algorithms required for management, scheduling, allocation
and communication used in operating system.
∙ All laboratory experiments, excluding the first, are to be included for
practical examination.
∙ Experiment distribution
o For questions having only one part: Students are allowed to pick one
experiment from thelot and are given equal opportunity.
o For questions having part A and B: Students are allowed to pick one
experiment frompart A and one experiment from part B and are given
equal opportunity.
∙ Change of experiment is allowed only once and marks allotted for procedure part
to be madezero.
∙ Marks Distribution (Subjected to change in accoradance with university regulations)
a) For questions having only one part – Procedure + Execution + Viva-Voce:
15+70+15 =100 Marks
b) For questions having part A and B
1. Part A – Procedure + Execution + Viva = 4 + 21 + 5 = 30 Marks
2. Part B – Procedure + Execution + Viva = 10 + 49+ 11 = 70 Marks
CONTENTS LIST
SL. EXPERIMENT NAME PAGE
NO NO
1. CHAPTER 1: Introduction to LEX 1
6. Program 1 : 20
a) Write a LEX program to recognize valid arithmetic
expression. Identifiers in the expression could be only
integers and operators could be + and *. Count the identifiers
& 22
operators present and print them separately.
b)Write YACC program to evaluate arithmetic
expression involving operators: +, -, *, and /
T1 = -B
T2 = C + D
T3 = T1 + T2
A = T3
11. Program 6 : 43
a) Write a LEX program to eliminate comment lines in a
C program and copy the resulting program into a separate 46
file.
b)Write YACC program to recognize valid identifier,
operators and keywords in the given text (C program) file.
CHAPTER1
Introduction to LEX
Lex and YACC helps you write programs that transforms structured input. Lex generates C code
for lexical analyzer where as YACC generates Code for Syntax analyzer. Lexical analyzer is build
using a tool called LEX. Input is given to LEX and lexical analyzer is generated.
Lex is a UNIX utility. It is a program generator designed for lexical processing of character input
streams. Lex generates C code for lexical analyzer. It uses the patterns that match strings in the
input and converts the strings to tokens. Lex helps you by taking a set of descriptions of possible
tokens and producing a C routine, which we call a lexical analyzer. The token descriptions that Lex
uses are known as regular expressions.
nd
2 Step: lex program1.l
rd
3 Step: cc lex.yy.c –ll
th
4 Step: ./a.out
%% is a delimiter to the mark the beginning of the Rule section. The second %% is optional,
but the first is required to mark the beginning of the rules. The definitions and the
code/subroutines are often omitted
Programming in Lex:
Programming in Lex can be divided into three steps:
Page 1
System Software Laboratory 18CSL66
Note: If the scanner is part of a parser developed using Yacc, only steps 1 and 2 should be
performed. Read the part B on Yacc.
Now let's look at the kind of program format that Lex understands. A Lex program is divided into
three sections:
∙ The first section has global C and Lex declarations (regular expressions). ∙
The second section has the patterns (coded in C)
In this section we can add C variable declarations. We will declare an integer variable here for
our word-counting program that holds the number of words counted by the program.
We'll also perform token declarations of Lex.
%{
int wordCount = 0;
%}
chars [A-za-z\_\'\.\"]
numbers ([0-9])+
%%
The double percent sign implies the end of this section and the beginning of the second of
the three sections in Lex programming.
Let's look at the Lex rules for describing the token that we want to match. (We'll use C to define
what to do when a token is matched.) Continuing with our word-counting program, here are the
rules for matching tokens.
{whitespace} { /* do nothing*/ }
%%
Page 2
System Software Laboratory 18CSL66 C code:
The third and final section of programming in Lex covers C function declarations (and
occasionally the main function)
Note that this section has to include the yywrap() function. Lex has a set of functions and variables
that are available to the user.
One of them is yywrap. Typically, yywrap() is defined as shown in the example below.
void main()
{
yylex(); /* start the analysis*/
int yywrap()
{
return 1;
In the preceding sections we've discussed the basic elements of Lex programming,which should
help you in writing simple lexical analysis programs
This produces the lex.yy.c file, which can be compiled using a C compiler. It can also be
used with a parser to produce an executable, or you can include the Lex library in the link
step with the option –ll.
yyout Of the type FILE*. This points to the location where the output of the
lexer will be
yytext The text of the matched pattern is stored in this variable (char*).
yylinen Provides current line number information. (May or may not be supported by
Page 3
System Software Laboratory 18CSL66 Lex functions
yylex() The function that starts the analysis. It is automatically generated by Lex.
yywrap() This function is called when end of file (or input) is encountered. If this
function returns 1, the parsing stops. So, this can be used to parse
multiple files. Code can be written in the third section, which will allow
multiple files to be parsed. The strategy is to make yyin file pointer (see
the preceding table) point to a different file until all the files are parsed.
At the end, yywrap() can return 1 to indicate end of parsing.
yyless(int This function can be used to push back all but first characters of the
) read token.
yymore() This function tells the lexer to append the next token to the current token.
Regular Expressions
It is used to describe the pattern. It is widely used to in lex. It uses meta language. The character
used in this Meta language is part of the standard ASCII character set.
An expression is made up of symbols.Normal symbols are characters and numbers, but there are
other symbols that have special meaning in Lex. The following two tables define some of the
symbols used in Lex and give a few typical examples
Character Meaning
A-Z, 0-9, a-z Characters and numbers that form part of the pattern.
Page 4
System Software Laboratory 18CSL66
^ Negation.
[0-9] 0 or 1 or 2 or………9
-?[0-9]+ -1 or +1 or +2 …..
The name is an acronym for ―Yet Another Compiler. YACC generates the code for the parser in
the C programming language. YACC was developed at AT& T for the UNIX operating system.
YACC has also been rewritten for other languages, including JAVA, ADA
The function parser calls the lexical analyzer to pick up the tokens from the input stream. These
tokens are organized according to the input structure rules .The input structure rule is called as
grammar. When one of the rule is recognized, then user code supplied for this rule (user code is
action) is invoked. Actions have the ability to return values and makes use of the values ofother
actions.
Steps
in writing YACC Program:
st
1 step: Using gedit editor create a file with extension y.
For example: program1.y
nd
2 Step: yacc –d program1.y
rd
3 Step: lex program1.l
th Step
4 : cc y.tab.c lex.yy.c -ll
th Step
5 : /a.out
Page 6
System Software Laboratory 18CSL66 When we run YACC, it generates a parser in file y.tab.c
and also creates an include file y.tab.h. To obtain tokens, YACC calls yylex. Function yylex has a
return type of int and returns the token. Values associated with the token are returned by lex in
variable yylval.
Every YACC specification file consists of three sections. The declarations, Rules (of
grammars), programs. The sections are separated by double percent “%%” marks. The %
is generally used in YACC specification as an escape character.
The general format for the YACC file is very similar to that of the Lex file.
1stCol 2ndCol 3rdCol 4thCol
DEFINITION SECTION
%%
RULE SECTION
%%
CODE SECTION
Definition Section
%union It defines the Stack type for the Parser. It is a union of various
datas/structures/ Objects
%token These are the terminals returned by the yylex function to the YACC. A
token can also have type associated with it for good type checking and
syntax directed translation. A type of a token can be specified as %token
<stack member>tokenName.
Ex: %token NAME NUMBER
%type The type of a non-terminal symbol in the Grammar rule can be specified
with this.The format is %type <stack member>non-terminal.
%noassoc Specifies that there is no associatively of a terminal symbol.
%start Specifies the L.H.S non-terminal symbol of a production rule which should
be taken as the starting point of the grammar rules.
%prec Changes the precedence level associated with a particular rule to that of
the following token name or literal
Page 7
System Software Laboratory 18CSL66
Rule Section
The rules section simply consists of a list of grammar rules. A grammar rule has the form:
A: BODY
A represents a nonterminal name, the colon and the semicolon are YACC punctuation and
BODY represents names and literals. The names used in the body of a grammar rule may
represent tokens or nonterminal symbols. The literal consists of a character enclosed in
single quotes.
Every name not defined in the declarations section is assumed to represent a non-terminal
symbol. Every non-terminal symbol must appear on the left side of at least one rule. Of all
the no terminal symbols, one, called the start symbol has a particular importance.
The parser is designed to recognize the start symbol. By default the start symbol is taken
to be the left hand side of the first grammar rule in the rules section.
With each grammar rule, the user may associate actions to be. These actions may return
values, and may obtain the values returned by the previous actions. Lexical analyzer can
return values for tokens, if desired. An action is an arbitrary C statement. Actions are
enclosed in curly braces.
Page 8
System Software Laboratory 18CSL66 CHAPTER 3
Introduction to UNIX
Basic UNIX commands
Up one folder cd ..
Remove directory-recursively rm -r
Copy old file to new file. -p preserve file attributes e.g. cp old.file new.file
ownership and edit dates)-r copy recursively through
directory structure -a archive, combines the flags-p – R
and-d
Page 9
System Software Laboratory 18CSL66 File Utilities
Action UNIX options & filespec
Calculator bc
calendar for September, 1752 (when leap years began) cal 9 1752
Page 10
System Software Laboratory 18CSL66
CHAPTER 4
Introduction to Operating System
An Operating System is a program that manages the Computer hardware. It controls and
coordinates the use of the hardware among the various application programs for the various users.
A Process is a program in execution. As a process executes, it changes state
∙ New : The process is being created
∙ Running : Instructions are beingexecuted
∙ Waiting : The process is waiting for some event to occur
∙ Ready : The process is waiting to be assigned to a process
∙ Terminated : The process has finished execution
Apart from the program code, it includes the current activity represented by
∙ ProgramCounter
∙ Contents of Processor registers,
∙ Process Stack which contains temporary data like functions parameters,
return addresses and local variables
A Multi-programmed system can have many processes running simultaneously with the CPU
multiplexed among them. By switching the CPU between the processes, the OS can make the
computer more productive. There is Process Scheduler which selects the process among many
processes that are ready, for program execution on the CPU. Switching the CPU to another process
Scheduling Algorithms
CPU Scheduler can select processes from ready queue based on various scheduling algorithms.
Different scheduling algorithms have different properties, and the choice of a particular algorithm
may favor one class of processes over another. The scheduling criteria include
∙ CPU utilization:
∙ Throughput: The number of processes that are completed per unit time.
∙ Waiting time: The sum of periods spent waiting in readyqueue.
∙ Turnaround time: The interval between the time of submission of process to the
time of completion.
∙ Response time: The time from submission of a request until the first response
is produced.
Page 11
System Software Laboratory 18CSL66
The different scheduling algorithms are
∙ First Come First Serve, is just like FIFO (First in First out) Queue data structure, where the
data element which is added to the queue first, is the one who leaves the queue first. ∙ This is
used in Batch Systems.
∙ It's easy to understand and implement programmatically, using a Queue data structure,
where a new process enters through the tail of the queue, and the scheduler selectsprocess
from the head of the queue.
∙ A perfect real life example of FCFS scheduling is buying tickets at ticket counter.
LRU page replacement policy is based on the observation that pages that have been heavily used
in the last few instructions will probably be heavily used again in the next few. Conversely, pages
that have not been used for ages will probably remain unused for a long time.
Shortest job first (SJF) or shortest job next, is a scheduling policy that selects the waiting process
with the smallest execution time to execute next. SJN is a non-preemptive algorithm.
∙ Shortest Job first has the advantage of having a minimum average waiting time among all
scheduling algorithms.
∙ It may cause starvation if shorter processes keep coming. This problem can be solved using
the concept of aging.
Page 12
System Software Laboratory 18CSL66
∙ It is practically infeasible as Operating System may not know burst time and therefore may
not sort them. While it is not possible to predict execution time, several methods can be
used to estimate the execution time for a job, such as a weighted average of previous
execution times. SJF can be used in specialized environments where accurate estimates of
running time are available
Page 13
System Software Laboratory 18CSL66
Banker’s Algorithm in Operating System
∙ Banker’s Algorithm is a resource allocation and deadlock avoidance algorithm. This algorithm
test for safety simulating the allocation for predetermined maximum possible amounts of all
resources, then makes an “s-state” check to test for possible activities, before decidingwhether
allocation should be allowed to continue.
∙ In simple terms, it checks if allocation of any resource will lead to deadlock or not, OR is it
safe to allocate a resource to a process and if not then resource is not allocated to that process.
Determining a safe sequence (even if there is only 1) will assure that system will not go into
deadlock.
∙ Banker’s algorithm is generally used to find if a safe sequence exists or not. But here we will
determine the total number of safe sequences and print all safe sequences.
Page 14
System Software Laboratory 18CSL66
CHAPTER 5
Sample Lex and Yacc Programs
Examples of sample Lex Program and Yacc Programs
Sample Program 1
%{
#include<stdio.h>
int cc=0,nn=0;
%}
%option noyywrap
%%
[a-zA-Z] cc++;
[0-9] nn++;
%%
main()
{
yylex();
printf("num of characters %d\nnum of numbers %d\n",cc,nn);
Output
student@student:~/naveen$ lex countnumbersletter.l
student@student:~/naveen$ cc lex.yy.c
student@student:~/naveen$ ./a.out
amith kumar
9912367987
ajay kumar
9531256834
num of characters 19
num of numbers 20
student@student:~/naveen$
Sample Program 2
%{
#include<stdio.h>
int wc=0;
%}
%option noyywrap
%%
[^ \t\n]+ wc++;
%%
Page 15
System Software Laboratory 18CSL66
main()
{
yylex();
printf("num of words %d\n",wc);
}
Output
student@student:~/naveen$ lex sample.l
student@student:~/naveen$ cc lex.yy.c
student@student:~/naveen$ ./a.out
BIET Colllege of Engineering
num of words 4
Sample Program 3
%{
#include<stdio.h>
int vc=0,cc=0;
%}
%option noyywrap
%%
[aeiouAEIOU] vc++;
[a-zA-Z] cc++;
%%
main()
{
printf("enter input\n");
yylex();
printf("num of vowels %d\n no of consonants %d\n",vc,cc);
}
Output
student@student:~/naveen$ lex vowelscount.l
student@student:~/naveen$ cc lex.yy.c
student@student:~/naveen$ ./a.out
enter input
BIET College of Engineering
num of vowels 11
no of consonants 13
student@student:~/naveen$
Sample Program 4
%{
#include<stdio.h>
int countcomment=0;
%}
Page 16
System Software Laboratory 18CSL66
%option noyywrap
%%
"/*"[^"*/"]*"*/" countcomment++;
"//".* countcomment++;
%%
main()
{
printf("enter comment lines\n");
yylex();
printf("No of Comments %d\n",countcomment);
}
Output
student@student:~/naveen$ lex countcomments.l
student@student:~/naveen$ cc lex.yy.c
student@student:~/naveen$ ./a.out
enter comment lines
// BIET College of Engineering
/* */
// this is ss os lab
/* Welcome* /
No of Comments 4
student@student:~/naveen$
Sample Program 5
Aim: Program to count the number of characters, words, spaces and lines in a given input
file.
%{
#include<stdio.h>
int wc,cc,lc,sc;
%}
word[^ \t\n]+
line[\n]
space[ ]
%%
{word} {wc++;cc+=yyleng;}
{line} {lc++;cc++;}
{space} {sc++;cc++;}
%%
int main(int argc,char * argv[])
{
if(argc!=2)
{
Page 17
System Software Laboratory 18CSL66
printf("\n\t Usage:./a.out filename\n");
return 0;
}
yyin=fopen(argv[1],"r");
yylex();
printf("\n Number of lines=%d",lc);
printf("\n Number of words=%d",wc);
printf("\n Number of character=%d",cc);
printf("\n Number of spaces=%d\n",sc);
return 0;
}
Output1
student@student:~/naveen$ lex countlswc.l
student@student:~/naveen$ cc lex.yy.c -ll
student@student:~/naveen$ cat a.txt
BIET college of engineering
student@student:~/naveen$ ./a.out a.txt
Number of lines=1
Number of words=4
Number of character=28
Number of spaces=3
student@student:~/naveen$
Output2
student@student:~/naveen$ lex countlswc.l
student@student:~/naveen$ cc lex.yy.c -ll
student@student:~/naveen$ cat b.txt
BIET college of
engineering
student@student:~/naveen$ ./a.out b.txt
Number of lines=2
Number of
Words=4Number of
character=26 Number of
spaces=3
student@student:~/naveen$
Sample Program 6
Aim:Program to recognize a valid variable, which starts with a letter, followed by any
number of letters or digits.
Lex part
%{
#include"y.tab.h"
%}
%option noyywrap
%%
[a-zA-Z]+ return l;
[0-9]+ return d;
[\t] ;
Page 18
System Software Laboratory 18CSL66
\n return 0;
. return yytext[0];
%%
Yacc part
%{
#include<stdio.h>
%}
%token l d
%%
var:l s {printf("valid variable");return 0;}
s:s l
|s d
|;
%%
main()
{
printf("enter the variable");
yyparse();
}
yyerror()
{
printf("invalid variable");
exit(0);
}
Page 19
System Software Laboratory 18CSL66
Program No.1a: Write a LEX program to recognize valid arithmetic
expression. Identifiers in the expression could be only integers and operators
could be + and *. Count the identifiers & operators present and print them
separately.
Program Objective :
%{
#include<stdio.h>
int id=0,op=0,b=0;
%}
%option noyywrap
%%
[a-zA-Z0-9]*[a-zA-Z]* {id++;printf("\t");ECHO;}
[+|-|*|/] {op++;printf("\t");ECHO;}
"(" b++;
")" b--;
%%
main()
{
printf("enter arthimetic expression \n");
yylex();
if((op+1==id) && b==0)
{
printf("valid expression\n");
printf("No of Identifers=%d\n",id);
printf("No of operators=%d\n",op);
}
else
printf("invalid expression\n");
}
Page 20
System Software Laboratory 18CSL66
Output 1
student@student:~/naveen$ lex program1.l
student@student:~/naveen$ cc lex.yy.c
student@student:~/naveen$ ./a.out enter
arthimetic expression
(1+2)
1+2
valid expression
No of Identifers=2
No of operators=1
Output 2
student@student:~/naveen$ lex program1.l
student@student:~/naveen$ cc lex.yy.c
student@student:~/naveen$ ./a.out enter
arthimetic expression
((1+2)*3)
1+2*3
valid expression
No of Identifers=3
No of operators=2
Output 3
student@student:~/naveen$ lex program1.l
student@student:~/naveen$ cc lex.yy.c
student@student:~/naveen$ ./a.out enter
arthimetic expression
((1+2)
1+2
invalid expression
Output 4
student@student:~/naveen$ lex program1.l
student@student:~/naveen$ cc lex.yy.c
student@student:~/naveen$ ./a.out enter
arthimetic expression
((1+2)*3
1+2*3
invalid expression
Page 21
System Software Laboratory 18CSL66
Program No.1b: Write YACC program to evaluate arithmetic expression
involving operators: +, -, *, and /.
lex part
%{
#include "y.tab.h"
extern int yylval;
%}
%%
[0-9]+ {yylval=atoi(yytext);return num;}
[\+\-\*\/] {return yytext[0];}
[)] {return yytext[0];}
[(] {return yytext[0];}
. {;}
\n {return 0;}
%%
yacc part
%{
#include<stdio.h>
#include<stdlib.h>
int yyerror();
int yylex();
%}
%token num
%left '+''-'
%left '*''/'
%%
input:exp{printf("%d\n",$$);exit(0);}
exp:exp'+'exp{$$=$1+$3;}
|exp'-'exp{$$=$1-$3;}
|exp'*'exp{$$=$1*$3;}
|exp'/'exp {if($3==0){printf("Divide by Zero\n");exit(0);} else
$$=$1/$3;}
|'('exp')'{$$=$2;}
|num{$$=$1;};
%%
int yyerror()
{
printf("error");
exit(0);
}
Page 22
System Software Laboratory 18CSL66
int main()
{
printf("enter expression\n");
yyparse();
}
Output1
student@student:~/naveen$ yacc -d program1b.y
student@student:~/naveen$ lex program1b.l
student@student:~/naveen$ cc y.tab.c lex.yy.c -ll
student@student:~/naveen$ ./a.out
enter expression
(2+4)*(2-8)
-36
student@student:~/naveen$
Output2
student@student:~/naveen$ yacc -d program1b.y
student@student:~/naveen$ lex program1b.l
student@student:~/naveen$ cc y.tab.c lex.yy.c -ll
student@student:~/naveen$ ./a.out
enter expression
5/0
Divide by Zero
Output3
student@student:~/naveen$ yacc -d program1b.y
student@student:~/naveen$ lex program1b.l
student@student:~/naveen$ cc y.tab.c lex.yy.c -ll
student@student:~/naveen$ ./a.out
enter expression
(2*5)/5
2
Page 23
System Software Laboratory 18CSL66
Program Outcome
Viva Questions:
∙ What is an Assembler?
Assembler for an assembly language, a computer program to
translate between lower-level representations of computer programs.
Page 24
System Software Laboratory 18CSL66
Program No. 2: Develop, Implement and execute a program using YACC tool
to recognize all strings ending with b preceded by n a’s using the grammar a n
b (note: input n value).
Program Objective :
lex part
%{
#include "y.tab.h"
%}
%%
a {return A;}
b {return B;}
. {return yytext[0];}
[\n] {return 0;}
%%
yacc part
%{
#include<stdio.h>
#include<stdlib.h>
int yylex();
int yyerror();
int count=0;
%}
%token A B
%%
s:A s{count++;}
|B
;
%%
int main()
{
int n;
printf("enter value for n\n");
scanf("%d",&n);
getchar();
printf("enter input string with a's and b's\n");
yyparse();
if(n==count)
printf("valid string\n");
Page 25
System Software Laboratory 18CSL66
else
yyerror();
return 0;
}
int yyerror()
{
printf("invalid string\n");
exit(0);
}
Output1
student@student-OptiPlex-390:~$ yacc -d program2.y
student@student-OptiPlex-390:~$ lex program2.l
student@student-OptiPlex-390:~$ cc y.tab.c lex.yy.c -ll
student@student-OptiPlex-390:~$ ./a.out
enter value for n
1
enter input string with a's and b's
ab
valid string
Output2
student@student-OptiPlex-390:~$ ./a.out
enter value for n
2
enter input string with a's and b's
aab
valid string
Output3
student@student-OptiPlex-390:~$ ./a.out
enter value for n
0
enter input string with a's and b's
b
valid string
Output4
student@student-OptiPlex-390:~$ ./a.out
enter value for n
0
enter input string with a's and b's
ab
invalid string
Page 26
System Software Laboratory 18CSL66
Output5
student@student-OptiPlex-390:~$ ./a.out
enter value for n
1
enter input string with a's and b's
aab
invalid string
Output6
student@student-OptiPlex-390:~$ ./a.out
enter value for n
1
enter input string with a's and b's
acb
invalid string
student@student-OptiPlex-390:~$
Program Outcome:
Viva Questions:
Page 27
System Software Laboratory 18CSL66
Program No. 3: Design, develop and implement YACC/C program to construct
Predictive / LL (1) Parsing Table for the grammar rules: A →aBa , B →bB | ε.
Use this table to parse the sentence: abba$.
Program Objective :
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char prod[3][10]={"A->aBa","B->bB","B->@"};
char first[3][10]={"a","b","@"};
char follow[3][10]={"$","a","a"};
char table[3][3][10];
char input[10];
int top=-1;
char stack[25];
char curp[20];
char new1[10],new2[10],new3[10],newstr[10];
char table2 [4][3][10] =
{
"NT", "a","b",
"A", "aBa","Error",
"B", "Error","bB",
"B", "Error","e",
};
Page 28
System Software Laboratory 18CSL66
int numr(char c)
{
switch(c)
{
case 'A': return 1;
case 'B': return 2;
case 'a': return 1;
case 'b': return 2;
case '@': return 3;
}
return(1);
}
void calulatefollow()
{
char str1[20]="A->aBa",str2[20]="B->bB",str3[20]="B->@";
int n1=6,n2=5,n3=4,i,j,k;
printf("\nFOLLOW SET \n");
printf("\n FOLLOW(A)=$\n");
for(i=3;i<n1;i++)
{
if(str1[i]=='B')
printf("FOLLOW(B)=%c",str1[5]);
newstr[0]=str1[5];
}
}
void main()
{
char c;
int i,j,k,n,n1=6;
char str1[20]="A->aBa",str2[20]="B->bB",str3[20]="B->@";
for(i=0;i<3;i++)
for(j=0;j<4;j++)
strcpy(table[i][j],"e");
printf("\n Grammar:\n");
for(i=0;i<3;i++)
printf("%s\n",prod[i]);
printf("\nfirst(A)= {%s}\n",first[0]);
printf("\nfirst(B)= {%s,%s}\n",first[1],first[2]);
calulatefollow();
strcpy(table[0][0]," ");
strcpy(table[0][1],"a");
Page 29
System Software Laboratory 18CSL66
strcpy(table[0][2],"b");
strcpy(table[0][3],"$");
strcpy(table[1][0],"A");
strcpy(table[2][0],"B");
for(i=0;i<3;i++)
{
k=strlen(first[i]);
for(j=0;j<k;j++)
if(first[i][j]!='@')
strcpy(table[numr(prod[i][0])][numr(first[i][j])],prod[i])
; else
strcpy(table[numr(prod[i][0])][numr(follow[i][j])],prod[i]);
}
printf("\n \n");
printf("\n LL(1) PARSER TABLE \n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%s\t",table[i][j]);
}
printf("\n");
}
printf("\n");
printf("\n \n");
printf("enter the input string terminated with $ to parse :- ");
scanf("%s",input);
for(i=0;input[i]!='\0';i++)
if((input[i]!='a')&&(input[i]!='b')&&(input[i]!='$'
)) {
printf("invalid string");
exit(0);
}
if(input[i-1]!='$')
{
printf("\n\nInput String Entered Without End marker $");
exit(0);
}
push('$');
push('A');
i=0;
printf("\n\n");
printf(" stack\t Input \taction ");
printf("\n - \n");
Page 30
System Software Laboratory 18CSL66
while(input[i]!='$' && stack[top]!='$')
{
display();
printf("\t\t%s\t ",(input+i));
if (stack[top]==input[i])
{
printf("\tmatched %c\n",input[i]);
pop();
i++;
}
else
{
if(stack[top]>=65 && stack[top]<92)
{
strcpy(curp,table[numr(stack[top])][numr(input[i])]
); if(!(strcmp(curp,"e")))
{
printf("\n invalid string- Rejected\n");
exit(0);
}
else
{
printf(" \tapply production %s\n",curp);
if(curp[3]=='@')
pop();
else
{
pop();
n=strlen(curp);
for(j=n-1;j>=3;j--)
push(curp[j]);
}
}
}
}
display();
printf("\t\t%s\t ",(input+i));
printf("\n \n"); if(stack[top]=='$' && input[i]=='$' )
{
Page 31
System Software Laboratory 18CSL66
printf("\n valid string - Accepted\n");
}
else
{
printf("\ninvalid string- Rejected\n");
}
}
Output
student@student-OptiPlex-390:~$ cc program3.c
student@student-OptiPlex-390:~$ ./a.out
Grammar:
A->aBa
B->bB
B->@
first(A)= {a}
first(B)= {b,@}
FOLLOW SET
FOLLOW(A)=$
FOLLOW(B)=a
Page 32
System Software Laboratory 18CSL66 Program No.4: Design, develop and
implement YACC/C program to demonstrate Shift Reduce Parsing technique for
the grammar rules: E →E+T | T, T →T*F | F, F → (E) | id and parse the
sentence: id + id * id.
Program Objective:
∙A parser is a compiler or interpreter component that breaks data into smaller elements
for easy translation into another language. A parser takes input in the form of a
sequence of tokens or program instructions and usually builds a data structure in the
form of a parse tree or an abstract syntax tree.
∙A parser's main purpose is to determine if input data may be derived from the start
symbol of the grammar.
Page 33
System Software Laboratory 18CSL66
Top-down Parsing
When the parser starts constructing the parse tree from the start symbol and then tries to
transform the start symbol to the input, it is called top-down parsing.
It means, if one derivation of a production fails, the syntax analyzer restarts the process
using different rules of same production. This technique may process the input string
more than once to determine the right production.
Bottom-up Parsing
Bottom-up parsing starts with the input symbols and tries to construct the parse tree up to
the start symbol.
∙ Shift-reduce parsing attempts to construct a parse tree for an input string beginning at
the leaves and working up towards the root. In other words, it is a process of
“reducing” (opposite of deriving a symbol using a production rule) a string w to the
start symbol of a grammar. At every (reduction) step, a particular substring matching
the RHS of a production rule is replaced by the symbol on the LHS of the production.
∙ A general form of shift-reduce parsing is LR (scanning from Left to right and using
Right-most derivation in reverse) parsing, which is used in a number of automatic
parser generators like Yacc, Bison, etc.
Page 34
System Software Laboratory 18CSL66
#include<stdio.h>
#include<string.h>
int k=0,z=0,i=0,j=0,c=0;
char a[16],ac[20],stk[15],act[10];
void check();
int main()
{
printf("GRAMMAR is:\n E->E+T|T \nT->T*F|F\nF->(E)|id\n");
printf("Enter input string\n");
gets(a);
c=strlen(a);
printf("stack \t input \t action\n");
printf("------\t ------\t ------\n");
printf("\n$%s\t%s$\t",stk,a);
for(k=0,i=0; j<c; k++,i++,j++)
{
if(a[j]=='i' && a[j+1]=='d')
{
strcpy(act,"SHIFT ");
stk[i]=a[j];
stk[i+1]=a[j+1];
stk[i+2]='\0';
a[j]=' ';
a[j+1]=' ';
printf("\n$%s\t%s$\t%sid",stk,a,act);
check();
}
else if(a[j]=='+'||a[j]=='*')
{
strcpy(act,"SHIFT ");
stk[i]=a[j];
stk[i+1]='\0';
a[j]=' ';
printf("\n$%s\t%s$\t%s%c",stk,a,act,stk[i]);
check();
}
else
{
printf("\nERROR IN INPUT\n");
break;
}
}
if(stk[0]=='E' && j==c)
printf("\n****SUCCESSFULL PARSING****\n");
Page 35
System Software Laboratory 18CSL66
else
printf("\n****FAILURE IN PARSING****\n");
}
void check()
{
strcpy(ac,"REDUCE F->id");
for(z=0; z<c; z++)
if(stk[z]=='i' && stk[z+1]=='d')
{
stk[z]='F';
stk[z+1]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
j++;
}
strcpy(ac,"REDUCE T->T*F");
for(z=0; z<c; z++)
if(stk[z]=='T' && stk[z+1]=='*' && stk[z+2]=='F')
{
stk[z]='T';
stk[z+1]='\0';
stk[z+2]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
i=i-2;
}
strcpy(ac,"REDUCE T->F");
for(z=0; z<c; z++)
if(stk[z]=='F' )
{
stk[z]='T';
stk[z+1]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
}
strcpy(ac,"REDUCE E->E+T");
for(z=0; z<c; z++)
{
if(stk[z]=='E' && stk[z+1]=='+' && stk[z+2]=='T' && stk[z+3]!='*' && a[j+1]!='*')
{
stk[z]='E';
stk[z+1]='\0';
stk[z+2]='\0';
stk[z+3]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
i=i-2;
}
Page 36
System Software Laboratory 18CSL66
else if(stk[z]=='E' && stk[z+1]=='+' && stk[z+2]=='T' && j==c)
{
stk[z]='E';
stk[z+1]='\0';
stk[z+2]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
i=i-2;
}
else
break;
}
strcpy(ac,"REDUCE E->T");
for(z=0; z<c; z++)
if(stk[z]=='T' )
{
if(a[j+1]=='+'||a[j+1]=='\0')
{
stk[z]='E';
stk[z+1]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
}
else
break;
}
strcpy(ac,"REDUCE F->(E)");
for(z=0; z<c; z++)
if(stk[z]=='(' && stk[z+1]=='E' && stk[z+2]==')')
{
stk[z]='F';
stk[z+1]='\0';
stk[z+1]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
i=i-2;
}
}
Page 37
System Software Laboratory 18CSL66
Output
student@localhost:~/naveen$ cc program4.c
student@localhost:~/naveen$ ./a.out
GRAMMAR is:
E->E+T|T
T->T*F|F
F->(E)|id
Enter input string
id+id*id
stack input action
--
$ id+id*id$
$id +id*id$ SHIFT id $F +id*id$ REDUCE
F->id $T +id*id$ REDUCE T->F $E
+id*id$ REDUCE E->T $E+ id*id$ SHIFT
+ $E+id *id$ SHIFT id $E+F *id$
REDUCE F->id $E+T *id$ REDUCE T->F
$E+T* id$ SHIFT * $E+T*id $ SHIFT id
$E+T*F $ REDUCE F->id $E+T $
REDUCE T->T*F $E $ REDUCE E->E+T
****SUCCESSFULL PARSING****
student@localhost:~/naveen$
Page 38
System Software Laboratory 18CSL66
Program Outcome :
Page 39
System Software Laboratory 18CSL66
Program No.5: Design, develop and implement a C/Java program to generate
the machine code using Triples for the statement A = -B * (C +D) whose
intermediate code in three-address form:
T1 = -B
T2 = C + D
T3 = T1 * T2
A = T3
Program Objective :
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
char op[2],arg1[5],arg2[5],result[5];
void main()
{
FILE *fp1,*fp2; fp1=fopen("input.txt","r");
fp2=fopen("output.txt","w");
while(!feof(fp1))
{
fscanf(fp1,"%s%s%s%s",result,arg1,op,arg2);
if(strcmp(op,"+")==0)
{
fprintf(fp2,"\nMOV R0,%s",arg1);
fprintf(fp2,"\nADD R0,%s",arg2);
fprintf(fp2,"\nMOV %s,R0",result);
}
if(strcmp(op,"*")==0)
{
fprintf(fp2,"\nMOV R0,%s",arg1);
fprintf(fp2,"\nMUL R0,%s",arg2);
fprintf(fp2,"\nMOV %s,R0",result);
}
if(strcmp(op,"-")==0)
{
fprintf(fp2,"\nMOV R0,%s",arg1);
fprintf(fp2,"\nSUB R0,%s",arg2);
fprintf(fp2,"\nMOV %s,R0",result);
}
Page 40
System Software Laboratory 18CSL66
if(strcmp(op,"/")==0)
{
fprintf(fp2,"\nMOV R0,%s",arg1);
fprintf(fp2,"\nDIV R0,%s",arg2);
fprintf(fp2,"\nMOV %s,R0",result);
}
if(strcmp(op,"=")==0)
{
fprintf(fp2,"\nMOV R0,%s",arg1);
fprintf(fp2,"\nMOV %s,R0",result);
}
}
fclose(fp1);
fclose(fp2);
}
Output
input.txt
T1 -B =?
T2 C + D
T3 T1 * T2
A T3 =?
student@localhost:~/naveen$ cc program5.c
student@localhost:~/naveen$ ./a.out
student@localhost:~/naveen$ cat output.txt
MOV R0,-B
MOV T1,R0
MOV R0,C
ADD R0,D
MOV T2,R0
MOV R0,T1
MUL R0,T2
MOV T3,R0
MOV R0,T3
MOV A,R0
MOV R0,T3
MOV A,R0
Page 41
System Software Laboratory 18CSL66
Program Outcome
∙ To implement a c program to generate a machine code
∙ To accept the input in a separate file and display it in a separate file
Viva Questions:
∙ Are Lexical Analysis and Parsing two different Passes? These two
can form two different passes of a Parser. The Lexical analysis can store all
the recognized tokens in an intermediate file and give it to the Parser as an
input. However it is more convenient to have the lexical Analyzer as a co
routine or a subroutine which the Parser calls whenever it requires a token.
∙ What are the Advantages of using Context-Free grammars? It
is precise and easy to understand.
It is easier to determine syntactic ambiguities and conflicts in the grammar.
∙ If Context-free grammars can represent every regularexpression,
why do one needs R.E at all?
Regular Expression are Simpler than Context-free grammars. It is easier
to construct a recognizer for R.E than Context-Free grammar. Breaking
the Syntactic structure into Lexical & non-Lexical parts provide better
front end for the Parser.
R.E are most powerful in describing the lexical constructs like identifiers,
keywords etc while Context-free grammars in representing the nested or
block structures of the Language.
Page 42
System Software Laboratory 18CSL66
Program No. 6a: Write a LEX program to eliminate comment lines in a C
program and copy the resulting program into a separate file.
Program Objective:
Page 43
System Software Laboratory 18CSL66
Output1
student@student:~$ lex program6.l
student@student:~$ cc lex.yy.c
student@student:~$ cat >a.c
#include<stdio.h>
main()
{
int a,b,c;
/* declaration */
printf("------------");
scanf(" -------- ");
// for reading
getch();
}
printf("------------");
scanf(" -------- ");
getch();
}
student@student:~$
Output2
student@student:~$ cat >a1.c
main()
{
int a,b,c;
printf(" ");
// simple comment
scanf(" -------- ");
// comment below scanf
getch();
/* multiple
comment */
// single line comment
}
Page 44
System Software Laboratory 18CSL66
student@student:~$ ./a.out a1.c b1.c
number of comment lines 4
student@student:~$ cat b1.c main()
{
int a,b,c;
printf("--------------");
scanf(" -------- ") ;
getch();
}
student@student:~$
Page 45
System Software Laboratory 18CSL66
Program No. 6b: WriteYACC program to recognize valid identifier, operators
and keywords in the given text (C program) file.
lex part
%{
#include <stdio.h>
#include "y.tab.h"
extern yylval;
%}
%%
[ \t] ;
[+|-|*|/|=|<|>] {printf("operator is %s\n",yytext);return OP;}
[0-9]+ {yylval = atoi(yytext); printf("numbers is %d\n",yylval); return DIGIT;}
int|char|bool|float|void|for|do|while|if|else|return|void {printf("keyword
is%s\n",yytext);return KEY;}
[a-zA-Z0-9]+ {printf("identifier is %s\n",yytext);return ID;}
.;
%%
yacc part
%{
#include <stdio.h>
#include <stdlib.h>
int yyerror();
int yylex();
int id=0, dig=0, key=0, op=0;
%}
%token DIGIT ID KEY OP
%%
input:
DIGIT input {dig++;}
| ID input {id++;}
| KEY input { key++; }
| OP input {op++;}
| DIGIT { dig++;}
| ID { id++;}
| KEY {key++;}
| OP {op++;}
;
%%
Page 46
System Software Laboratory 18CSL66
#include <stdio.h>
extern int yylex();
extern int yyparse();
extern FILE *yyin;
main()
{
FILE *myfile = fopen("input.c", "r");
if (!myfile)
{
printf("I can't open input.c!");
return -1;
}
yyin = myfile;
do
{
yyparse();
}
while (!feof(yyin));
printf("Number of numbers = %d\n Number ofKeywords = %d\n Number of
Identifiers = %d\n Number of noperators = %d\n",dig, key,id, op); }
int yyerror()
{
printf("error");
exit(0);
}
Output
input.c
void main()
{
int a;
float b;
char c;
char d;
int sum=40;
if(sum>=40)
printf("---pass--");
else
printf("---fail--");
}
Page 47
System Software Laboratory 18CSL66
student@localhost:~/naveen$ yacc -d program6b.y
student@localhost:~/naveen$ lex program6b.l
student@localhost:~/naveen$ cc y.tab.c lex.yy.c -ll
student@localhost:~/naveen$ ./a.out
keyword is void
identifier is main
keyword is int
identifier is a
keyword is float
identifier is b
keyword is char
identifier is c
keyword is char
identifier is d
keyword is int
identifier is sum
operator is =
numbers is 40
keyword is if
identifier is sum
operator is >
operator is =
numbers is 40
identifier is printf
identifier is pass
keyword is else
identifier is printf
identifier is fail
Number of numbers = 2
Number of Keywords = 8
Number of Identifiers = 11
Number of n operators = 3
student@localhost:~/naveen$
Page 48
System Software Laboratory 18CSL66
Program Outcome :
Viva Questions :
Non-Terminals:- These are syntactic variables in the grammar which represents a set
of strings the grammar is composed of. In a Parse tree all the inner nodes represents
the Non-Terminal symbols.
Page 49
System Software Laboratory 18CSL66
Program No. 7: Design, develop and implement a C/C++/Java program to
simulate the working of shortest remaining time and Round Robin (RR)
scheduling algorithms. Experiment with different quantum sizes for RR
algorithm.
Program Objective:
Theory
Round Robin scheduling algorithm is one of the most popular scheduling algorithm which
can actually be implemented in most of the operating systems. This is the preemptive version
of first come first serve scheduling. The Algorithm focuses on Time Sharing
In this algorithm, every process gets executed in a cyclic way. A certain time slice is defined
in the system which is called time quantum. Each process present in the ready queue is
assigned the CPU for that time quantum, if the execution of the process is completed during
that time then the process will terminate else the process will go back to the ready queue and
waits for the next turn to complete the execution.
Some important characteristics of the Round Robin (RR) Algorithm are as follows: ∙
Round Robin Scheduling algorithm resides under the category of Preemptive Algorithms. ∙
This algorithm is one of the oldest, easiest, and fairest algorithms.
∙ This Algorithm is a real-time algorithm because it responds to the event within a specific
time limit.
∙ In this algorithm, the time slice should be the minimum that is assigned to a specific task
that needs to be processed. Though it may vary for different operating systems. ∙ This is a
hybrid model and is clock-driven in nature.
∙ This is a widely used scheduling method in the traditional operating system.
Important terms
1. Completion Time It is the time at which any process completes its execution. 2. Turn
Around Time This mainly indicates the time Difference between completion time and arrival
time. The Formula to calculate the same is: Turn Around Time = Completion Time –
Arrival Time
3. Waiting Time(W.T): It Indicates the time Difference between turn around time and burst
time. And is calculated as Waiting Time = Turn Around Time – Burst Time
Page 50
System Software Laboratory 18CSL66
Graphical Representation of Round Robin Algorithm
Page 51
System Software Laboratory 18CSL66
/* Round Robin Program in C*/
#include<stdio.h>
int main()
{
int i,j,n,time,x,counter=0,time_quantum;
int wait_time=0,turnaround_time=0,at[10],bt[10],rt[10];
printf("Enter Total Process:\t ");
scanf("%d",&n);
x=n;
for(i=0;i<n;i++)
{
printf("Enter Arrival Time and Burst Time for Process Process Number %d :",i+1);
scanf("%d",&at[i]);
scanf("%d",&bt[i]);
rt[i]=bt[i];
}
printf("Enter Time Quantum:\t");
scanf("%d",&time_quantum);
printf("\n\nProcess\t|Turnaround Time|Waiting Time\n\n");
for(time=0,i=0;x!=0;)
{
if(rt[i]<=time_quantum && rt[i]>0)
{
time+=rt[i];
rt[i]=0;
counter=1;
}
else if(rt[i]>0)
{
rt[i]-=time_quantum;
time+=time_quantum;
}
if(rt[i]==0 && counter==1)
{
x--;
printf("P[%d]\t|\t%d\t|\t%d\n",i+1,time-at[i],time-at[i]-bt[i]);
wait_time+=time-at[i]-bt[i];
turnaround_time+=time-at[i];
counter=0;
}
if(i==n-1)
i=0;
else if(at[i+1]<=time)
Page 52
System Software Laboratory 18CSL66
i++;
else
i=0;
}
printf("\nAverage Waiting Time= %.2f\n",wait_time*1.0/n);
printf("Average Turnaround Time = %.2f",turnaround_time*1.0/n);
return 0;
}
Output1
student@student:~/naveen$ cc program7rr.c
student@student:~/naveen$ ./a.out
Enter Total Process: 3
Enter Arrival Time and Burst Time for Process Process Number 1 :0 7
Enter Arrival Time and Burst Time for Process Process Number 2 :2 4
Enter Arrival Time and Burst Time for Process Process Number 3 :4 1
Enter Time Quantum: 3
Output2
student@student:~/naveen$ cc program7rr.c
student@student:~/naveen$ ./a.out
Enter Total Process: 4
Enter Arrival Time and Burst Time for Process Process Number 1 :0 10
Enter Arrival Time and Burst Time for Process Process Number 2 :1 4
Enter Arrival Time and Burst Time for Process Process Number 3 :2 5
Enter Arrival Time and Burst Time for Process Process Number 4 :3 3
Enter Time Quantum: 4
Page 53
System Software Laboratory 18CSL66
Average Waiting Time= 9.25
Average Turnaround Time = 14.75
student@student:~/naveen$
Output3
student@student:~/naveen$ cc program7rr.c
student@student:~/naveen$ ./a.out
Enter Total Process: 5
Enter Arrival Time and Burst Time for Process Process Number 1 :0 8
Enter Arrival Time and Burst Time for Process Process Number 2 :1 1
Enter Arrival Time and Burst Time for Process Process Number 3 :2 3
Enter Arrival Time and Burst Time for Process Process Number 4 :3 2
Enter Arrival Time and Burst Time for Process Process Number 5 :4 6
Enter Time Quantum: 3
import java.util.Scanner;
{
public static void main(String[] args)
{
int i,j,n,time,x,counter=0,time_quantum;
int wait_time=0,turnaround_time=0;
Scanner sn=new Scanner(System.in);
int[] at = new int[20];
int[] bt = new int[20];
int[] rt = new int[20];
System.out.println("Enter Total Process:\t ");
n=sn.nextInt();
x=n;
for(i=0;i<n;i++)
{
System.out.println("Enter Arrival Time for Process");
at[i]=sn.nextInt();
System.out.println("Enter burst time of process "+i);
bt[i]=sn.nextInt();
rt[i]=bt[i];
}
System.out.println("Enter Time Quantum:\t");
time_quantum=sn.nextInt();
System.out.println("\n\nProcess\t|Turnaround Time|Waiting Time");
for(time=0,i=0;x!=0;)
{
if(rt[i]<=time_quantum && rt[i]>0)
{
time+=rt[i];
rt[i]=0;
counter=1;
}
else if(rt[i]>0)
{
rt[i]-=time_quantum;
time+=time_quantum;
}
Page 55
System Software Laboratory 18CSL66
if(rt[i]==0 && counter==1)
{
x--;
System.out.print("process"+i+"\t");
System.out.print(time-at[i]+"\t");
System.out.print("\t");
System.out.print(time-at[i]-bt[i]);
System.out.println("\t");
wait_time+=time-at[i]-bt[i];
turnaround_time+=time-at[i];
counter=0;
}
if(i==n-1)
i=0;
else if(at[i+1]<=time)
i++;
else
i=0;
}
System.out.println("\n Average Waiting Time="+wait_time*1.0/n);
System.out.println("Average Turnaround Time ="+turnaround_time*1.0/n);
}
}
Output 1
Enter Total Process:
3
Enter Arrival Time for Process
0
Enter burst time of process 0
7
Enter Arrival Time for Process
2
Enter burst time of process 1
4
Enter Arrival Time for Process
4
Enter burst time of process 2
1
Enter Time Quantum:
3
Page 56
System Software Laboratory 18CSL66
Process |Turnaround Time |Waiting Time Process 2 3 2
Process 1 9 5 Process 0 12 5
Output2
Page 57
System Software Laboratory 18CSL66
Output3
Enter Total Process:
5
Enter Arrival Time for Process
0
Enter burst time of process 0
6
Enter Arrival Time for Process
0
Enter burst time of process 1
5
Enter Arrival Time for Process
0
Enter burst time of process 2
2
Enter Arrival Time for Process
0
Enter burst time of process 3
3
Enter Arrival Time for Process
0
Enter burst time of process 4
7
Enter Time Quantum:
2
Output 4
Enter Total Process:
6
Enter Arrival Time for Process
0
Enter burst time of process 0
4
Enter Arrival Time for Process
Page 58
System Software Laboratory 18CSL66
1
Enter burst time of process 1
5
Enter Arrival Time for Process
2
Enter burst time of process 2
2
Enter Arrival Time for Process
3
Enter burst time of process 3
1
Enter Arrival Time for Process
4
Enter burst time of process 4
6
Enter Arrival Time for Process
6
Enter burst time of process 5
3
Enter Time Quantum:
2
Page 59
System Software Laboratory 18CSL66
Shortest Remaining Time First (SRTF) Scheduling Algorithm
∙ The Preemptive version of Shortest Job First(SJF) scheduling is known as Shortest Remaining
Time First (SRTF). With the help of the SRTF algorithm, the process having the smallest
amount of time remaining until completion is selected first to execute. So basically in SRTF,
the processes are scheduled according to the shortest remaining time.
∙ However, the SRTF algorithm involves more overheads than the Shortest job first
(SJF)scheduling, because in SRTF OS is required frequently in order to monitor the
CPU time of the jobs in the READY queue and to perform context switching.
∙ In the SRTF scheduling algorithm, the execution of any process can be stopped after a
certain amount of time. On arrival of every process, the short-term scheduler schedules
those processes from the list of available processes & running processes that have the
least remaining burst time.
∙ After all the processes are available in the ready queue, then, No preemption will be done
and then the algorithm will work the same as SJF scheduling. In the Process Control
Block, the context of the process is saved, when the process is removed from the
execution and when the next process is scheduled. The PCB is accessed on the next
execution of this process
Advantages of SRTF
∙ The main advantage of the SRTF algorithm is that it makes the processing of the jobs
faster than the SJF algorithm, mentioned it’s overhead charges are not counted.
Disadvantages of SRTF
∙ In SRTF, the context switching is done a lot more times than in SJN due to more
consumption of the CPU's valuable time for processing. The consumed time of CPUthen
adds up to its processing time and which then diminishes the advantage of fast
processing of this algorithm.
Page 60
System Software Laboratory 18CSL66
/* Shortest Remaining Time Program in C*/
#include<stdio.h>
int n,qtum,pid[10],a[10],b[10],tt[10],avg[10];
int swt=0,stat=0;
float f_avg_turn_arnd_time=0.0,f_avg_wait_time=0.0;
int main()
{
int ch;
int a[10],b[10],x[10],i,smallest, count=0,time=0,n;
double avg=0,tt=0,end;
printf("enter the number of processes:\n");
scanf("%d",&n);
printf("enter arrival time\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("enter the burst time \n");
for(i=0;i<n;i++)
scanf("%d",&b[i]);
for(i=0;i<n;i++)
x[i]=b[i];
b[9]=9999;
for(time=0;count!=n;time++)
{
smallest=9;
for(i=0;i<n;i++)
{
if(a[i]<=time && b[i]<b[smallest] && b[i]>0)
smallest=i;
}
b[smallest]--;
if(b[smallest]==0)
{
count++;
end=time+1;
avg=avg+end-a[smallest]-x[smallest];
tt=tt+end-a[smallest];
}
}
printf("\n average waiting time = %.2lf\n",avg/n);
printf("average turn around time = %.3lf",tt/n);
return 1;
}
Page 61
System Software Laboratory 18CSL66
Output 1
student@student:~/naveen$ cc program7srt.c
student@student:~/naveen$./a.out enter the
number of processes:
4
enter arrival time
0
1
2
4
enter the burst time
5
3
4
1
Output 2
student@student:~/naveen$ cc program7srt.c
student@student:~/naveen$./a.out enter the
number of processes:
5
enter arrival time
3
1
4
0
2
enter the burst time
1
4
2
6
3
Page 62
System Software and Operating System Laboratory 18CSL66
Output 3
student@student:~/naveen$ cc program7srt.c
student@student:~/naveen$./a.out
enter the number of processes:
5
enter arrival time
0
1
2
3
4
enter the burst time
8
4
2
1
3
Page 64
System Software and Operating System Laboratory 18CSL66
}
}
// end of outer for loop
System.out.println("\n average waiting time = "+avg/n);
System.out.format("average turn around time= %.2f",tt/n);
}
Output1
enter the number of processes:
4
Enter Arrival Time for Process :0
0
Enter Arrival Time for Process :1
1
Enter Arrival Time for Process :2
2
Enter Arrival Time for Process :3
4
Enter burst Time for Process :0
5
Enter burst Time for Process :1
3
Enter burst Time for Process :2
4
Enter burst Time for Process :3
1
Output2
enter the number of processes:
5
Enter Arrival Time for Process :0
0
Enter Arrival Time for Process :1
1
Enter Arrival Time for Process :2
2
Enter Arrival Time for Process :3
3
Enter Arrival Time for Process :4
4
Page 65
System Software and Operating System Laboratory 18CSL66
Enter burst Time for Process :0 8
Enter burst Time for Process :1 4
Enter burst Time for Process :2 2
Enter burst Time for Process :3 1
Enter burst Time for Process :4 3
Output3
enter the number of processes:
6
Enter Arrival Time for Process :0 0
Enter Arrival Time for Process :1 1
Enter Arrival Time for Process :2 2
Enter Arrival Time for Process :3 3
Enter Arrival Time for Process :4 4
Enter Arrival Time for Process :5 5
Enter burst Time for Process :0 7
Enter burst Time for Process :1 5
Enter burst Time for Process :2 3
Enter burst Time for Process :3 1
Enter burst Time for Process :4 2
Enter burst Time for Process :5 1
Page 66
System Software and Operating System Laboratory 18CSL66
Program Outcome :
Viva Questions:
The Parsing method is which the Parse tree is constructed from the input language
string beginning from the leaves and going up to the root node.Bottom-Up parsing is
also called shift-reduce parsing due to its implementation. The YACC supports shift
reduce parsing.
∙ What is the need of Operator precedence?
The shift reduce Parsing has a basic limitation. Grammars which can represent a left
sentential parse tree as well as right-sentential parse tree cannot be handled by shift
reduce parsing. Such a grammar ought to
Page 67
System Software and Operating System Laboratory 18CSL66
Program No. 8: Design, develop and implement a C/C++/Java program to
implement Banker’s algorithm. Assume suitable input required to demonstrate
the results.
Program Objective :
∙ To understand Deadlocks
∙ To understand the Bankers algorithm
Theory
Page 68
System Software and Operating System Laboratory 18CSL66
printf("enter the allocation\n");
for(j=0;j<r;j++)
scanf("%d",&f[i].all[j]);
printf("enter the max \n");
for(j=0;j<r;j++)
scanf("%d",&f[i].max[j]);
f[i].flag=0;
}
printf("enter avialable resuruces\n");
for(i=0;i<r;i++)
scanf("%d",&avail[i]);
printf("enter new request details\n");
printf("enter new pid \n");
scanf("%d",&id);
printf("enter request for resuruces\n");
for(i=0;i<r;i++)
{
scanf("%d",&newr);
f[id].all[i]+=newr;
avail[i]=avail[i]-newr;
}
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{
f[i].need[j]=f[i].max[j]-f[i].all[j];
if(f[i].need[j]<0)
f[i].need[j]=0;
}
}
cnt=0;
fl=0;
while(cnt!=n)
{
g=0;
for(j=0;j<n;j++)
{
if(f[j].flag==0)
{
b=0;
for(p=0;p<r;p++)
{
if(avail[p]>=f[j].need[p])
else
Page 69
System Software and Operating System Laboratory 18CSL66
b=b-1;
}
if(b==r)
{
printf("\np%d is visited",j);
// put processes in to safe sequence array
seq[fl++]=j;
f[j].flag=1;
for(k=0;k<r;k++)
avail[k]=avail[k]+f[j].all[k];
cnt=cnt+1;
printf("(");
for(k=0;k<n;k++)
printf("%3d",avail[k]); // print new allocation resources
printf(")");
g=1;
}
}
}
if(g==0)
{
printf("request is not granted Dead lock occured\n");
printf("system is in un safe state\n");
goto y;
}
}
printf("\n system is in safe state\n");
printf(" safe sequence is ");
for(i=0;i<fl;i++)
printf("P%d",seq[i]);
y:
printf("\n process \t allocation \t max \t need\n");
for(i=0;i<n;i++)
{
printf("P%d\t",i);
for(j=0;j<r;j++)
printf(" %3d",f[i].all[j]);
for(j=0;j<r;j++)
printf(" %3d",f[i].max[j]);
for(j=0;j<r;j++)
printf(" %3d",f[i].need[j]);
printf("\n");
}
}
Page 70
System Software and Operating System Laboratory 18CSL66
Output1
student@student:~/naveen$ cc program8.c
student@student:~/naveen$ ./a.out enter
the number of processess
5
enter the number of resources
3
enter the details of p 0
enter the allocation
010
enter the max
753
enter the details of p 1
enter the allocation
200
enter the max
322
enter the details of p 2
enter the allocation
302
enter the max
902
enter the details of p 3
enter the allocation
211
enter the max
222
enter the details of p 4
enter the allocation
002
enter the max
433
p 1 is visited(422)
p 3 is visited(633)
Page 71
System Software and Operating System Laboratory 18CSL66
p 4 is visited(635)
p 0 is visited(755)
p 2 is visited(1057)
student@student:~/naveen$ ./a.out
enter the number of processess
5
enter the number of resources
4
enter the details of p 0
enter the allocation
0012
enter the max
0012
enter the details of p 1
enter the allocation
1000
enter the max
1756
enter the details of p 2
enter the allocation
1354
enter the max
2356
enter the details of p 3
enter the allocation
0632
enter the max
0652
enter the details of p 4
enter the allocation
0014
Page 72