SS 0slab 15csl67

You might also like

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

HKBK COLLEGE OF ENGINEERING

(Affiliated to VTU, Belgaum and Approved by AICTE)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

15CSL67
SYSTEM SOFTWARE AND OPERATING SYSTEM LABORATORY
[As per Choice Based Credit System (CBCS) scheme]

MANUAL

PREPARED BY

Mrs. Smitha Kurian Mrs. Tabassum Ara Mrs. Manjula HT

Mrs. Rashmi Purad

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
HKBK COLLEGE OF ENGINEERING
Nagawara, Bangalore -560 045
www.hkbkeducation.org

Number of Lecture Hours/Week 01I + 02P Exam Marks 80


Total Number of Lecture Hours 40 Exam Hours 03
CREDITS – 02
Course objectives: This course will enable students to
• To make students familiar with Lexical Analysis and Syntax Analysis phases of Compiler
Design and implement programs on these phases using LEX & YACC tools and/or
C/C++/Java
• To enable students to learn different types of CPU scheduling algorithms used in operating
system.
• To make students able to implement memory management - page replacement and deadlock
handling algorithms
Description (If any):
Exercises to be prepared with minimum three files (Where ever necessary): i.
Header file.
ii. Implementation file.
iii. Application file where main function will be present.
The idea behind using three files is to differentiate between the developer and user sides. In the
developer side, all the three files could be made visible. For the user side only header file and
application files could be made visible, which means that the object code of the implementation file
could be given to the user along with the interface given in the header file, hiding the source file, if
required. Avoid I/O operations (printf/scanf) and use data input file where ever it is possible
Study Experiment / Project:
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.
Conduction of Practical Examination:
• All laboratory experiments are to be included for practical examination.
• Students are allowed to pick one experiment from the lot.
• Strictly follow the instructions as printed on the cover page of answer script
• Marks distribution: Procedure + Conduction + Viva:20 + 50 +10 (80)
• Change of experiment is allowed only once and marks allotted to the procedure part to
be made zero

Programme Outcomes:

a. Engineering Knowledge: Apply knowledge of mathematics, science, engineering


fundamentals and an engineering specialization to the solution of complex engineering
problems.

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
b. Problem Analysis: Identify, formulate, research literature and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural
sciences and engineering sciences
c. Design/ Development of Solutions: Design solutions for complex engineering problems and
design system components or processes that meet specified needs with appropriate
consideration for public health and safety, cultural, societal and environmental considerations.
d. Conduct investigations of complex problems using research-based knowledge and research
methods including design of experiments, analysis and interpretation of data and synthesis of
information to provide valid conclusions.
e. 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 under- standing of the limitations.
f. The Engineer and Society: Apply reasoning informed by contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
professional engineering practice.
g. Environment and Sustainability: Understand the impact of professional engineering
solutions in societal and environmental contexts and demonstrate knowledge of and need for
sustainable development.
h. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of engineering practice.
i. Individual and Team Work: Function effectively as an individual, and as a member or
leader in diverse teams and in multi disciplinary settings.
j. Communication: 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
clear instructions.
k. 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.
l. Project Management and 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 environments.

Programme Specific Outcomes

m. Problem-Solving Skills: An ability to investigate and solve a problem by analysis,


interpretation of data, design and implementation through appropriate techniques, tools and
skills.
n. Professional Skills: An ability to apply algorithmic principles, computing skills and
computer science theory in the modelling and design of computer-based systems.
o. Entrepreneurial Ability: An ability to apply design, development principles and
management skills in the construction of software product of varying complexity to become
an entrepreneur

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
Mapping of Course outcome to Programme Outcomes

PO a b c d e f g H I j K L m n o

CO

1 3 3 2 222 22 11 11 -- 3 1 2 2 3 3 3

2 3 3 2 22 22 1 1 - 3 1 2 2 3 3 3

3 - High correlation
2 - Moderate(Medium)correlation
1 - Slight(low)Some correlation
- - No correlation

Lab Experiments:
Sl Experiment
No.
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.
b) Write YACC program to evaluate arithmetic expression involving operators: +, -, *,
and /
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 an b (note: input n value)

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$
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.
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
6. a) Write a LEX program to eliminate comment lines in a C program and copy
the resulting program into a separate file.
b) Write YACC program to recognize valid identifier, operators and keywords
in the given text (C program) file.

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
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.
8. Design, develop and implement a C/C++/Java program to implement Banker’s algorithm.
Assume suitable input required to demonstrate the results.
9. Design, develop and implement a C/C++/Java program to implement page replacement
algorithms LRU and FIFO. Assume suitable input required to demonstrate the results.

10 a) Design, develop and implement a C/C++/Java program to simulate a


numerical calculator
b) Design, develop and implement a C/C++/Java program to simulate page
replacement technique

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
Programs
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:1.l
%{
#include<stdio.h>
int v=0,op=0,id=0,flag=0;
%}
%%
[0-9][0-9]* {id++;printf("\n Identifier:");ECHO;}
[\+\-\*\/\=] {op++;printf("\n Operartor:");ECHO;}
"(" {v++;}
")" {v--;}
";" {flag=1;}
.|\n {;}
%%
int main()
{
printf("Enter the expression ");
yylex();
if((op+1) ==id && v==0 && flag==0)
{
printf("\n Identifiers are:%d Operators are:%d\n",id,op);

printf("\n Expression is Valid\n");


}
else
printf("\n Expression is Invalid\n");
return 1;
}
int yywrap()
{
return 1;
}

TESTCASE INPUT OUTPUT STATUS


1 2+1 Identifier:2
Operator:+
Identifier:3
Identifiersare:2
Operators are:1
Expression is valid
2 2+ Identifier:2
Operator:+
Expression is invalid
3 2+1*3+8 Identifier:2
Operator:+
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
Identifier:1
Operator:*
Identifier:3
Operator:+
Identifier:8
Identifiers are:4
Operators are:4
Expression is valid
4 2+1*3+8- Identifier:2
Operator:+
Identifier:1
Operator:*
Identifier:3
Operator:+
Identifier:8
Operator:-
Expression is invalid
5 +2+5 Operator:+
Identifier:2
Operator:+
Identifier:5
Identifiers are:2
Operators are:2
Expression is valid

Viva Questions
Sl.No Questions
1. What is Lex?
Ans: It is a computer program that generates lexical analyzers (“scanners or
lexers”).
2. Who developed Lex
Ans: Lex originally written by Mike Lesk and Eric Schmidt described in 1975
3. What does LEX stands for
Ans: Lexical analyser generator
4. Is lex open source?
Ans: Yes lex is open source
5. Lex works on which OS
Ans: lex works on all the flavours of UNIX operating system
6. Structure of a lex program
Ans: It consists of three sections or blocks namely:
1. Definition section: Global and local declarations, #define statements,
2. Rules section: It has three parts namely a)Pattern part and b)action part
If pattern is recognised action will be executed
3. User subroutine section:
7. Define yylex()
Ans: It is a lexical analyzer function. It recognizes tokens from the input stream
and returns them to the parser.

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
8. What is yywrap()
Ans: It is called by lex when the input is exhausted and it returns 1 if EOF or o
if more processing is required
9. What is ECHO
Ans: lex predefined variable. Used to write match string
10. What are identifiers?
Ans: Identifiers are symbols used to uniquely identify a program element in the
code. They are used to refer to types, constants, macros and parameters.
11. What is operator?
Ans: An operator is symbol that tells the compiler to perform specific
mathematical or logical functions.
12. What are regular expression
Ans: It is a sequence of characters that define a search pattern
13. What are the special characters used in a regular expression
Ans
Pattern Matches
. any character except newline
\. literal .
\n newline
\t tab
^ beginning of line
$ end of line
14. What are the operators used in regular expression
Ans:
Pattern Matches
* zero or more copies of the preceding expression
+ one or more copies of the preceding expression
a|b a or b (alternating)
(ab)+ one or more copies of ab (grouping)
Abc abc
abc* ab abc abcc abccc ...
abc+ abc abcc abccc abcccc ...
a(bc)+ abc abcbc abcbcbc ...
a(bc)? a abc

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
1b)Write YACC program to evaluate arithmetic expression involving operators: +, -,*, and /
Program:1b.l
%{
#include<stdio.h>
#include<ctype.h>
%}
%token DIG
%left '+' '-'
%left '*' '/'
%left UMINUS
%%
line : line exp '\n' {printf("Res=%d\n",$2);}
|
| line '\n'
| error '\n' {yyerror("Invalid Exp:\n");yyerrok; }
;

exp : exp '+' exp {$$=$1+$3;}


| exp '-' exp {$$=$1-$3;}
|exp '*' exp {$$=$1*$3;}
|exp '/' exp {if($3==0)
{
printf("\n Divide by 0 error\n");
return 0;
}
else
$$=$1/$3;
}
| '-'exp %prec UMINUS {$$=-$2;}
| num
;
num : DIG {$$=$1;}
| num DIG {$$=$1*10+$2;}
;
%%
main()
{
printf(“Enter The Valid Arithmetic Expression\n”);
yyparse();
}
yyerror(char *s)
{
printf("%s\n",s);
}
yylex()
{
int c;
while((c=getchar())==' '); //Accept single character and store it in c then terminate
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
if(isdigit(c)) //built in function to recognize digit
{
yylval=c-'0'; //yylval is variable to store hex values
return DIG;
}
return c;
}

Test Cases INPUT OUTPUT STATUS


1 2+3*5 Res=17
2 2*3+5 Res=11

3 2+3*2-1 Res=7

4 2*3+5+1 Res=12
5 2+3- Error
Invalid Exp

VIVA Questions
Sl.No Questions
1. What is YACC?
Ans: It is a tool for automatically generating a parser given a grammar Written
in a YACC specification (.y file)
2. Abbreviation of YACC?
Ans: Yet Another Compiler Compiler
3. Who developed YACC?
Ans:
4. What is Grammar?
Ans: It specifies a set of production rules, which define a language
5. What is a production rule?
Ans: A production rule specifies a sequence of symbols, sentences, which are
Legal in the language
6. Structure of a YACC specification file
Ans: Consists of three sections namely
1.Definition section
declarations of tokens
type of values used on parser stack
2.Rules section
list of grammar rules with semantic routines
3.User code section
yyparse();
7. What is yyparse()?
Ans: It reads a stream of token/value pairs from yylex() which needs to be
supplied
8. What is yyerror()

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
Ans: It is an error action function
9. What is yylval?
Ans: values associated with the token are returned by lex in a variable called
yylval
10. How to declare a terminal names
Ans: Terminal or token names can be declared using the %token declaration and
non-terminal names can be declared using the %type declaration.
11. Is it required to declare a %type declaration for a non-terminal names
Ans: No, they are defined automatically if they appear on the left side of at one
rule.
12. Define YACC keywords
Ans:%left, %nonassoc, %right, %start, %token, %type, %union
13. YACC keywords and description
Ans:
Keyword Description
%left Identifies tokens that are left associative with other tokens
%nonassoc Identifies tokens that are not associative with other tokens
%right Identifies tokens that are right associative with other tokens
%start Identifies a nonterminal name for the start symbol
%token Identifies the token names that the YACC command accepts.
Declares all token names in the declaration section are left
associative with other tokens
%type Identifies the type of nonterminal. Type checking is performed
when this construct is present.
%union Identifies the YACC value stack as the union of the various
type of values desired.
14. What is yyerrok?
Ans: It resets the parse to its normal mode.
15. What is isdigit() function
Ans: It is a function which can be used to check if a passed character is a digit or
not.it returns a non-zero value if it is a digit else it returns zero.
16. What is getchar() function
Ans: reads a single character from the standard input stream stdin, and it returns
to the program.

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
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 anb (note: input n value)
Program:2.y
%{
#include<stdio.h>
#include<ctype.h>
%}
%token A B
%%
line : line str '\n' {printf("\n Valid string\n");}
|
| error '\n' {yyerror("\n Invalid string\n"); yyerrok;}
;

str : A s1 B|B
s1 : | A s1
;
%%
int main()
{
yyparse(); // call the rule section
}
yyerror(char *s) //built in function to display error message
{
printf("%s\n",s);
}
yylex()
{
int c;
while((c=getchar())==' '); //Accept single character and store it in c then terminate
if(c =='a' || c =='A') return A; //match input character with a or A
if(c =='b' || c =='B') return B; //match input character with b or B
return c;
}

TESTCASE INPUT OUTPUT STATUS


1 B Valid string
2 A Invalid string
3 *23 Error
4 Bba Invalid string
5 aaaaaaaaaaaab valid string

Viva Questions
Sl.No Questions
1. What is a string?
Ans: It is an array of characters. The length of a string is determined by a
terminating null character ‘\0’

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
2. What is yyparse()?
Ans: It reads a stream of token/value pairs from yylex() which needs to be
supplied
3. What is yyerror()
Ans: It is an error action function
4. What is getchar() function
Ans: reads a single character from the standard input stream stdin, and it returns
to the program.

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
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:3.c
/* A ->aBa , B ->bB | @*/
#include<stdio.h>
#include<string.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][4][10];
char input[10];
int top=-1;
char stack[25];
char curp[20];
push(char item)
{
stack[++top]=item;
}
pop()
{
top=top-1;;
}
display()
{
int i;
for(i=top;i>=0;i--)
printf("%c",stack[i]);
}

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 main()
{
char c;
int i,j,k,n;
for(i=0;i<3;i++)
for(j=0;j<4;j++)

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
strcpy(table[i][j],"e");
printf("\n Grammar:\n");
for(i=0;i<3;i++)
printf("%s\n",prod[i]);
printf("\nfirst= {%s,%s,%s}",first[0],first[1],first[2]);
printf("\nfollow ={%s %s}\n",follow[0],follow[1]);
printf("\nPredictive parsing table for the given grammar\n");
strcpy(table[0][0]," ");
strcpy(table[0][1],"a");
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");
for(i=0;i<3;i++)
for(j=0;j<4;j++)
{
printf("%-10s",table[i][j]);
if(j==3) 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 ");
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
printf("\n--------------------------------------------------------\n");
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]=='$' )
{
printf("\n valid string - Accepted\n");
}
else
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
{
printf("\ninvalid string- Rejected\n");
}
}

TESTCASE INPUT OUTPUT SATUS


1. aba stack Input action
--------------------------------------------------------
A$ aba apply production A->aBa
aBa$ aba matched a
Ba$ ba apply production B->bB
bBa$ ba matched b
Ba$ a apply production B->@
a$ a matched a
--------------------------------------------------------
valid string – Accepted
2. ab stack Input action
--------------------------------------------------------
A$ ab apply production A->aBa
aBa$ ab matched a
Ba$ b apply production B->bB
bBa$ b matched b
--------------------------------------------------------
invalid string- Rejected
3. abba stack Input action
--------------------------------------------------------
A$ abba apply production A->aBa
aBa$ abba matched a
Ba$ bba apply production B->bB
bBa$ bba matched b
Ba$ ba apply production B->bB
bBa$ ba matched b
Ba$ a apply production B->@
a$ a matched a
--------------------------------------------------------
valid string – Accepted
4. abbb OUTPUT: stack Input action
--------------------------------------------------------
A$ abbb apply production A->aBa
aBa$ abbb matched a
Ba$ bbb apply production B->bB
bBa$ bbb matched b
Ba$ bb apply production B->bB
bBa$ bb matched b
Ba$ b apply production B->bB
bBa$ b matched b
--------------------------------------------------------
invalid string- Rejected
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
5. abbba stack Input action
--------------------------------------------------------
A$ abbba apply production A->aBa
aBa$ abbba matched a
Ba$ bbba apply production B->bB
bBa$ bbba matched b
Ba$ bba apply production B->bB
bBa$ bba matched b
Ba$ ba apply production B->bB
bBa$ ba matched b
Ba$ a apply production B->@
a$ a matched a
--------------------------------------------------------
valid string – Accepted
VIVA QUESTIONS
Sl.NO QUESTIONS
1. What is compiler?
Ans: It is a special program that translates high level language into machine level
language
2. What are the different phases of the compiler?
Ans: Lexical Analysis, syntax Analysis, Semantic Analysis, Intermediate code
generation, Code Optimization, code generation and symbol table
Explain the different types of parsers
Ans: Universal-It can parse any grammar
Top Down-suitable for LL grammar
Bottom Up-suitable for LR grammar
3. What is Top Down parsing
Ans: Top down parsing constructs a parse tree for the input string. Starting from the root
it creates the nodes of the parse tree in preorder. It finds a leftmost derivation for the input
string
4. Define CFG
Ans:Formal Definition G=(T,NT,S,P)
1. Terminals – Example: a,b
2. Nonterminals – Example- S,A
3. Start Symbol- Example S
4. Production- Example S->aAa
5. What is FIRST(α )?
Ans: FIRST(α ) for a grammar symbol α is defined as the set of terminals that begin with
strings derived from α.  If α =>  , then  is also in FIRST(α ).
6. What is FOLLOW(A) ?
Ans: FOLLOW(A) for a nonterminal A is defined as to be the set of terminals a that can
appear immediately to the right of A in some sentential form
7. What is Predictive / LL(1) Parsing
Ans: It is a Top down parser(LL(1)recursive descent)
8. What is LL(1)recursive descent
Ans: It constructs left most derivation(forwards), input: read left to right and 1 input
symbol lookahead

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
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:4.c
/*E -> E+T | T, T ->T*F | F, F ->(E) | id */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char ip_sym[15],stack[15];
int ip_ptr=0,st_ptr=0,len,i;
char temp[2];
char act[15];
void check();
void main()
{
printf("\n\t\t SHIFT REDUCE PARSER\n");
printf("\n GRAMMER\n");
printf("\n E->E+T|T\n T->T* F | F");
printf("\n F-> (E) | id \n ");
printf("\n enter the input symbol:\t");
scanf("%s",ip_sym);
printf("\n\t stack implementation table\n");
printf("\n stack\t\t input symbol\t\t action");
printf("\n______\t\t ____________\t\t ______\n");
printf("\n $\t\t%s$\t\t--",ip_sym); /*first step empty action */
strcpy(act,"shift ");
if (ip_sym[ip_ptr]=='(')
{
temp[0]=ip_sym[ip_ptr];
temp[1]='\0';
}
else
{
temp[0]=ip_sym[ip_ptr];
temp[1]=ip_sym[ip_ptr+1];
temp[2]='\0';
}
strcat(act,temp);
len=strlen(ip_sym);
for(i=0;i<=len-1;i++)
{
if(ip_sym[ip_ptr]=='i' &&ip_sym[ip_ptr+1]=='d')
{
stack[st_ptr]=ip_sym[ip_ptr];
st_ptr++;
ip_sym[ip_ptr]=' ';
ip_ptr++;
stack[st_ptr]= ip_sym[ip_ptr];
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
stack[st_ptr+1]='\0';
ip_sym[ip_ptr]=' ';
ip_ptr++;
}
else
{
stack[st_ptr]=ip_sym[ip_ptr];
stack[st_ptr+1]='\0';
ip_sym[ip_ptr]=' ';
ip_ptr++;
}
printf("\n $%s\t\t%s$\t\t%s",stack,ip_sym,act); /* second print with action shift*/
strcpy(act,"shift ");
if (ip_sym[ip_ptr]=='(' || ip_sym[ip_ptr]=='*' || ip_sym[ip_ptr]=='+' || ip_sym[ip_ptr]==')')
{
temp[0]=ip_sym[ip_ptr];
temp[1]='\0';
}
else
{
temp[0]=ip_sym[ip_ptr];
temp[1]=ip_sym[ip_ptr+1];
temp[2]='\0';
}
strcat(act,temp);
check();
st_ptr++;
}
st_ptr++;
check();
}
void check()
{
int flag=0;
while(1)
{
if (stack[st_ptr]=='d'&& stack[st_ptr-1]=='i')
{
stack[st_ptr-1]='F';
stack[st_ptr]='\0';
st_ptr--;
flag=1;
printf("\n $%s\t\t%s$\t\tF->id",stack, ip_sym);
}
if (stack[st_ptr]==')' && stack[st_ptr-1]=='E' && stack[st_ptr-2]=='(')
{
stack[st_ptr-2]='F';
stack[st_ptr-1]='\0';
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
flag=1;
st_ptr=st_ptr-2;
printf("\n $%s\t\t%s$\t\tF->id",stack, ip_sym);
}
if (stack[st_ptr]=='F' && stack[st_ptr-1]=='*' && stack[st_ptr-2]=='T')
{
// stack[st_ptr-2]='T';
stack[st_ptr-1]='\0';
st_ptr= st_ptr-2;
flag=1;
printf("\n $%s\t\t%s$\t\t\T->T*F",stack, ip_sym);
}
else
{
if (stack[st_ptr]=='F')
{
stack[st_ptr]='T';
flag=1;
printf("\n $%s\t\t%s$\t\tT->F",stack, ip_sym);
}
}
if( stack[st_ptr]=='T' && stack[st_ptr-1]=='+' && stack[st_ptr-2]=='E' && ip_sym[ip_ptr]!='*' )
{
//stack[st_ptr-2]='E';
stack[st_ptr-1]='\0';
st_ptr= st_ptr-2;
flag=1;
printf("\n $%s\t\t%s$\t\tE->E+T",stack, ip_sym);
}
else
if ((stack[st_ptr]=='T' && ip_sym[ip_ptr]== '+') || (stack[0]=='T' && ip_sym[ip_ptr]== '\0') ||
(stack[st_ptr]=='T' && ip_sym[ip_ptr]== ')'))
{
stack[st_ptr]='E';
flag=1;
printf("\n $%s\t\t%s$\t\tE->T",stack, ip_sym);
}
if((stack[st_ptr]=='T' && ip_sym[ip_ptr]== '*') ||
(stack[st_ptr]=='E' && ip_sym[ip_ptr]==')')||
(stack[st_ptr]=='E' && ip_sym[ip_ptr]=='+')||
(stack[st_ptr]=='+'&& ip_sym[ip_ptr]=='i' && ip_sym[ip_ptr+1]=='d')||
( stack[st_ptr]== '(' && ip_sym[ip_ptr]=='i' && ip_sym[ip_ptr+1]=='d') ||
(stack[st_ptr]== '(' && ip_sym[ip_ptr]=='(')||
(stack[st_ptr]=='*'&& ip_sym[ip_ptr]=='i' && ip_sym[ip_ptr+1]=='d' ) ||
(stack[st_ptr]=='*'&& ip_sym[ip_ptr]=='(') ||
(stack[st_ptr]=='+'&& ip_sym[ip_ptr]=='(')
)
{
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
flag=2;
}
if(!strcmp(stack,"E")&& ip_sym[ip_ptr]=='\0')
{
printf("\n $%s\t\t%s$\t\tACCEPT",stack,ip_sym);
getch();
exit(0);
}
if(flag==0)
{
printf("\n%s\t\t\t%s\t\treject",stack,ip_sym);
exit(0);
}
if (flag==2)
return;
flag=0;
}
}

TESTCASE INPUT OUTPUT STATUS


1 id+id*id stack implementation table
stack input symbol action
$ id+id*id$ --
$id +id*id$ shift id
$F +id*id$ F->id
$T +id*id$ T->F
$E +id*id$ E->T
$E+ id*id$ shift +
$E+id *id$ shift id
$E+F *id$ F->id
$E+T *id$ T->F
$E+T* id$ shift *
$E+T*id $ shift id
$E+T*F $ F->id
$E+T $ T->T*F
$E $ E->E+T
$E $ ACCEPT
2 id+id stack implementation table
stack input symbol action
$ id+id$ --
$id +id$ shift id
$F +id$ F->id
$T +id$ T->F
$E +id$ E->T
$E+ id$ shift +
$E+id $ shift id
$E+F $ F->id
$E+T $ T->F
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
$E $ E->E+T
$E $ ACCEPT
3 id-id*id stack implementation table
stack input symbol action
$ id-id*id$ --
$id -id*id$ shift id
$F -id*id$ F->id
$T -id*id$ T->F
T -id*id reject
4 id*id stack implementation table
stack input symbol action
$ id*id$ --
$id *id$ shift id
$F *id$ F->id
$T *id$ T->F
$T* id$ shift *
$T*id $ shift id
$T*F $ F->id
$T $ T->T*F
$E $ E->T
$E $ ACCEPT
5 id OUTPUT: stack implementation table
stack input symbol action
$ id$ --
$id $ shift id
$F $ F->id
$T $ T->F
$E $ E->T
$E $ ACCEPT

VIVA QUESTIONS
SL. No Questions
1. What is bottom-up parsing
Ans: A bottom-up parse corresponds to the construction of a parse tree for an input string
beginning at the leaves (the bottom) and working up towards the root (the top).
2. What is handle?
Ans: A "handle" is a substring that matches the body of a production.
3. What are the key decisions during bottom-up parsing
Ans: The key decisions during bottom-up parsing are about when to reduce and what
production to apply, as the parse proceeds
4. How to apply reduction in bottom up parsing
Ans: Reduction is the reverse of a derivation
5. What is shift reduce parsing?
Ans: Shift-reduce parsing is a form of bottom-up parsing in which
1. A stack holds grammar symbols and
2. An input buffer holds the rest of the string to be parsed.
3. Handle always appears at the top of the stack just before it is identified as the

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
handle.
4. $ is used to mark the bottom of the stack and also the right end of the input
6. What are the primary Operations of shift reduce parsing?
Ans:
1.Shift
2. Reduce
3.Accept
4.Error
7. What are the conflicts During Shift-Reduce Parsing?
Ans:
1. Shift Reduce conflict- here the parser cannot decide whether to shift or reduce
2. Reduce Reduce conflict- Out of the several reductions available, parser cannot
choose one reduction

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
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:5.c
#include<stdio.h>
#include<stdio.h>
//#include<conio.h>
#include<string.h>
void main()
{
char icode[10][30],opr;
char op1[5],op2[5],res[5];
int i=0,n,j,k;
printf("\nenter the number of intermediate statements");
scanf("%d", &n);
printf("\n Enter the set of intermediate code \n");
for(i=0;i<n;i++)
{
scanf("%s",icode[i]);
}
printf("\n");
for(i=0;i<n;i++)
{
j=0,k=0;
while(icode[i][j]!='=')
{
res[k]=icode[i][j];
j=j+1;
k=k+1;
}
res[j]='\0';
k=0;
j++;
if (icode[i][j] == '-')
{
j++;
while(icode[i][j]!='\0')
{
op1[k]=icode[i][j];
j++;
k++;
}
op1[k]='\0';
printf("\nLoad R1,%s \n",op1);
printf("NEG R1\n");
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
printf("STORE %s,R1\n",res);
}
else
{
k=0;
while(icode[i][j]!='\0' && icode[i][j]!='+' && icode[i][j]!='-' )
{
op1[k]=icode[i][j];
j++;
k++;
}
op1[k]='\0';
if(icode[i][j]=='\0')
{
printf("\nLoad R4,%s \n",op1);
printf("STORE %s,R4\n",res);
continue;
}
else
{
opr=icode[i][j];
k=0;
j++;

while(icode[i][j]!='\0' )
{
op2[k]=icode[i][j];
j++;
k++;
}
op2[k]='\0';
}
switch(opr)
{
case '+' : printf("\nLoad R2,%s \n",op1);
printf("Load R3,%s \n",op2);
printf("ADD R1,R1,R2\n");
printf("STORE %s,R1\n",res);
break;
case '-' : printf("\nLoad R2,%s \n",op1);
printf("Load R3,%s \n",op2);
printf("SUB R1,R1,R2\n");
printf("STORE %s,R1\n",res);
default: printf("\ninvalid statement\n");
}
}
}
}
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
TESTCASE INPUT OUTPUT STATUS
Number of intermediate Set of
statements intermediate
code
1. 4 T1=-B T1=-B
T2=C+D T2=C+D
T3=T1+T2 T3=T1+T2
A=T3 A=T3

Load R1,B
NEG R1
STORE T1,R1

Load R2,C
Load R3,D
ADD R1,R2
STORE T2,R1

Load R2,T1
Load R3,T2
ADD R1,R2
STORE T3,R1

Load R4,T3
STORE A,R4
3. 2 T1=B Load R4,B
T2=C STORE T1,R4

Load R4,C
STORE T2,R4
4. 1 add a Load R4,�
STORE add,R4

Load R4,�
STORE a,R4
*** stack
smashing
detected ***:
./a.out
terminated
Aborted (core
dumped)
5. 3 T1=B Load R4,B
T2=B+C STORE T1,R4
T3=C+D

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
Load R2,B
Load R3,C
ADD R1,R2
STORE T2,R1

Load R2,C
Load R3,D
ADD R1,R2
STORE T3,R1

VIVA QUESTIONS
SL.NO QUESTIONS
1. What is Three-address code?
Ans:
Three-address code is built from two concepts:
1.Addresses and
2. Instructions.
2. What is address?
Ans: An address can be one of the following:
1.Name
2.constant or Variables
3.A compiler-generated temporary
3. List the common three address instructions
Ans:
1.Assignment Instructions- x = y op z, x = op y
2.Copy instructions of the form x = y
3.An unconditional jump goto L
4. Conditional jumps of the form if x goto L and if False x goto L.
5.Conditional jumps such as if x relop y goto L

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
6 a)Write a LEX program to eliminate comment lines in a C program and copy the resulting
program into a separate file.
Program:6a.l
%{
int c=0;
%}
%x CMT
%x ct
%%
"//" {BEGIN ct ;}
<ct>.\n {c++; BEGIN INITIAL ;}
<ct>. ;
"/*" {BEGIN CMT ;}
<CMT>\n {c++ ;}
<CMT>.\n {c++ ;}
<CMT>"*/" {c++; BEGIN INITIAL ;}
<CMT>. ;
%%
int main (int argc, char *argv[])
{
FILE *fp1,*fp2;
if (argc==3)
{
fp1=fopen (argv [1],"r");
fp2=fopen (argv [2],"w");
yyin=fp1;
yyout=fp2;
}
yylex ();
}
int yywrap()
{
return 1;
}

TESTCASE INPUT OUTPUT STATUS


1. //This is a simple c program #include<stdio.h>
#include<stdio.h> main()
main() {
{ Printf(“Welcome to ss &Os lab”);
/* }
Body of a main program*/
Printf(“Welcome to ss &Os lab”);
}
2. //program
/*
Nothing
*/
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
3. //********************** #include<stdio.h>
#include<stdio.h> main()
main() {
{ }
}
4. //welcome
//to ss & Os lab
5. //This is a simple c program #include<stdio.h>
#include<stdio.h> main()
main() {
{ int a,b,c;
/* c=a+b;
Add two numbers Printf(“print c”);
*/ }
int a,b,c;
c=a+b;
Printf(“print c”);
}

Viva Questions
SL. No Questions
1. How to define a start condition
Ans: Start condition should be defined in the definition section of the lex specification
file by using a line in the following form
%start name1 name2
Here name1 and name2 are to define names that represent conditions.
2. How to use start condition in the rule section
Ans: by using the symbol <> at the beginning of the rule section ie<name1>expression
3. What is BEGIN and INITIAL
Ans:
BEGIN name1This statement changes the start condition to name1
BEGIN INTIAL or BEGIN 0This statement resets the lex program to the initial
condition.
4. What is int main(int argc, char *argv[])?
Ans: It is a command line argument
argcno of comments in the command line argument
char* argv[]array of pointers
Difference between char *argv[] and char **argv
Ans: char *argv[]array of pointers
Char** argvpointer to a char pointer
5. What is FILE *fp
Ans: fp means “file pointer” for example when using fopen function to open a file, a
FILE pointer is returned. FILE is a kind of structure that holds information about the
file.
6. What is fopen()?
Ans: This function opens the filename pointed to, by filename using the given mode.
Declaration:

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
FILE *fopen( const char *filename, const char*mode)
Parameters:
Filename-This is the c string containing the name of the file to be opened.
Mode-This is the c string containing a file access mode
“r”opens a file in read only mode.
“w”creates an empty file for writing.
This function returns a file pointer
7. What is yyin in lex
Ans: The input stream pointer (it points to an input file which is to be scanned or
tokenised) the default input of default main() is stdin.
8. What is yyout?
Ans: The output stream pointer (it points to a file where it has to keep the output). the
default input of default main() is stdout

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
6b) Write YACC program to recognize valid identifier, operators and keywords in the given text
(C program) file.
Program:6b.l
%{
#include<stdio.h>
int count=0;
%}
op [\+\-\*\/\=]
nop[\,\;\””]
letter [a-zA-Z]
digitt [0-9]
id {letter}*|({letter}{digitt})+
notid ({digitt}{letter})+
%%
[\t\n]+
("int")|("float")|("char")|("case")|("default")|("if")|("for")|("printf")|("scanf") {printf("%s is a
keyword\n", yytext);}
{id} {printf("%s is an identifier\n", yytext); count++;}
"+"|"-"|"*"|"/"|"=" {printf( "An operator: %s\n", yytext);}
{notid} {printf("%s is not an identifier\n", yytext);}
“,”|”;”|””” {;}
%%
int main()
{
FILE *fp;
char file[10];
printf("\nEnter the filename: ");
scanf("%s", file);
fp=fopen(file,"r");
yyin=fp;
yylex();
printf("Total identifiers are: %d\n", count);
return 0;
}
yywrap()
{
return 1;
}

TESTCASE INPUT OUTPUT STATUS


1. int a,b,c; int is a keyword
float d; a is identifier
b is identifier
c is identifier
float is a keyword
d is identifier
2. int a,b int is a keyword
res=c+d a is identifier
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
float e,f b is identifier
res is identifier
= is operator
c is identifier
+ is operator
d is identifier
float is keyword
e is identifier
f is identifier

VIVA Questions
SL. No Question
1. What are identifiers?
Ans: An identifiers can only have alphanumeric characters (a-z,A-Z,0-9) and
underscore(_).
2. What are keywords?
Ans: Keywords are predefined reserved words used in programming that have
special meanings to the compiler.
3. What is yyin in lex
Ans: The input stream pointer (it points to an input file which is to be scanned or
tokenised) the default input of default main() is stdin.
4. What is yyout?
Ans: The output stream pointer (it points to a file where it has to keep the
output). the default input of default main() is stdout

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
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
File Name: os_first.java

package OS_FIRST;
import java.io.*;
public class OS_FIRST {
public static void main(String[] args)
{
int ch=0;
do{
try{
System.out.println("Menu...");
System.out.println("1... SRT");
System.out.println("2... RR");
System.out.println("Enter your choice..:");
DataInputStream in=new DataInputStream(System.in);
ch=Integer.parseInt(in.readLine());
switch(ch)
{
case 1: srt s=new srt(); s.create_proc(); s.disp(); s.findavgTime(s.proc, s.n);
break;
case 2: rr r=new rr(); r.create_proc(); r.disp(); r.findavgTime(r.proc, r.n);
break;

}
}catch(Exception e){}
}while(ch<=2&& ch>0);
}
}

File Name: process.java


package OS_FIRST;

public class Process


{
int pid; // Process ID
int bt; // Burst Time
int art; // Arrival Time

public Process(int pid, int bt, int art)


{
this.pid = pid;
this.bt = bt;
this.art = art;
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
}
}

File Name: rr.java


package OS_FIRST;

import java.io.DataInputStream;
public class rr{
int i,n;
int no,bt,at,q;
Process proc[]= new Process[10];
public void create_proc()
{
try{

DataInputStream in=new DataInputStream(System.in);


System.out.println("Enter the number of process");
n=Integer.parseInt(in.readLine());
for(i=0;i<n;i++)
{
System.out.println("Enter the burst time and arrival time of process "+ i+1);
bt=Integer.parseInt(in.readLine());
at=Integer.parseInt(in.readLine());
proc[i]=new Process(i+1,bt,at);
}
System.out.println("Enter Time quantum:");
q=Integer.parseInt(in.readLine());
}catch(Exception e){}

public void disp()


{
System.out.println("p_id\tB_time\tA_Time");
for(i=0;i<n;i++)
{

System.out.println(proc[i].pid+"\t"+proc[i].bt+"\t"+proc[i].art);

}
System.out.println("Quantum : "+ q);
}

void findavgTime(Process proc[], int n)


{
System.out.println("function statred");
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
int wt[] = new int[n], tat[] = new int[n];
int 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


System.out.println("Processes " + " Burst time " +
" Waiting time " + " Turn around time");

// 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];
System.out.println(" " + (i+1) + "\t\t" + proc[i].bt +"\t " +
wt[i] +"\t\t " + tat[i]);
}

System.out.println("Average waiting time = " +


(float)total_wt / (float)n);
System.out.println("Average turn around time = " +
(float)total_tat / (float)n);
}

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];
}

void findWaitingTime(Process proc[], int n , int wt[])


{
System.out.println("findwaiting time is strated");
int rem_bt[] = new int[n];
for (int i = 0 ; i < n ; i++)

rem_bt[i] = proc[i].bt;

int t = 0; // Current time

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
while(true)
{
boolean done = true;

// Traverse all processes one by one repeatedly


for (int i = 0 ; i < n; i++)
{
if (rem_bt[i] > 0)
{
done = false; // There is a pending process

if (rem_bt[i] > q)
{
t += q;

rem_bt[i] -= q;
}

else
{
t = t + rem_bt[i];

wt[i] = t -proc[i].bt-proc[i].art;

rem_bt[i] = 0;
}
}
}
if (done == true)
break;
}
}
}

File Name: srt.java


package OS_FIRST;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.InputStreamReader;

public class srt{

public int i,n;


String no,bt,at;
public Process proc[]= new Process[10];
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
public void create_proc()
{
try{

DataInputStream in=new DataInputStream(System.in);


BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the number of process");
n=Integer.parseInt(in.readLine());
for(i=0;i<n;i++)
{
System.out.println("Enter the burst time and arrival time of process "+ i+1);

bt= bufferedReader.readLine();
at= bufferedReader.readLine();
proc[i]=new Process(i+1,Integer.parseInt(bt),Integer.parseInt(at));
}

}catch(Exception e){}

public void disp()


{
System.out.println("p_id\tB_time\tA_Time");
for(i=0;i<n;i++)
{

System.out.println(proc[i].pid+"\t"+proc[i].bt+"\t"+proc[i].art);

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

findWaitingTime(proc, n, wt);

findTurnAroundTime(proc, n, wt, tat);

System.out.println("Processes " +
" Burst time " +
" Waiting time " +
" Turn around time");

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


Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
System.out.println(" " + proc[i].pid + "\t\t"
+ proc[i].bt + "\t\t " + wt[i]
+ "\t\t" + tat[i]);
}

System.out.println("Average waiting time = " +


(float)total_wt / (float)n);
System.out.println("Average turn around time = " +
(float)total_tat / (float)n);
}
void findWaitingTime(Process proc[], int n,
int wt[])
{
int rt[] = new int[n];

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


rt[i] = proc[i].bt;

int complete = 0, t = 0, minm = Integer.MAX_VALUE;


int shortest = 0, finish_time;
boolean check = false;

while (complete != n) {

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


{
if ((proc[j].art <= t) &&
(rt[j] < minm) && rt[j] > 0) {
minm = rt[j];
shortest = j;
check = true;
}
}

if (check == false) {
t++;
continue;
}

rt[shortest]--;

minm = rt[shortest];
if (minm == 0)
minm = Integer.MAX_VALUE;

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
if (rt[shortest] == 0) {
complete++;
finish_time = t + 1;

wt[shortest] = finish_time -
proc[shortest].bt -
proc[shortest].art;

if (wt[shortest] < 0)
wt[shortest] = 0;
}
t++;
}
}

// Method to calculate turn around time


static void findTurnAroundTime(Process proc[], int n,
int wt[], int tat[])
{
for (int i = 0; i < n; i++)
tat[i] = proc[i].bt + wt[i];
}

TESTCASE INPUT OUTPUT STATUS


1. 1 1 8 0
01 8 0 2 4 1
11 4 1 3 9 2
21 9 2 4 5 3
31 5 3
1 8 9 17
2 4 0 4
3 9 15 24
4 5 2 7

6.5
13.0
2. 1 01 8 0 8
0
01 8 0 8.0
3. 1 1 0 0 0
0
1 0 0 0
4. 2
1 8 0
01 8 0 2 4 1
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
11 4 1 3 9 2
21 9 2 4 5 3
31 5 3
4

4 1 8 12 20
2 4 3 7
3 9 15 24
4 5 17 22

11.75
18.25

5. 1
1 24 6 30
1 24 0 2 3 4 7
2 3 1 3 3 7 10
3 3 2
5.66
15.66

VIVA
1 When we use Round Robin (RR)?
2 What is Turnaround time?
3 What is Waiting time?
4 What is Response time?
5 How to compute below times in Round Robin using a program?

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
8. Design, develop and implement a C/C++/Java program to implement Banker’s algorithm.
Assume suitable input required to demonstrate the results

File Name: os_second.java


package OS_SECOND;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.InputStreamReader;

public class OS_SECOND {

public static void main(String args[])


{
int n,res;
Bankers bn;
try
{
DataInputStream in=new DataInputStream(System.in);
System.out.println("Enter the number of processes:");
n=Integer.parseInt(in.readLine());
System.out.println("Enter the number of resources:");
res=Integer.parseInt(in.readLine());
bn=new Bankers(n,res);
bn.read_data();
bn.print_data();
bn.safety();

}catch(Exception e){}

}
}

File Name: Bankers.java

package OS_SECOND;

import java.io.DataInputStream;

public class Bankers {


public int proc_id[]= new int [10];
public int avail[]=new int[10];
public int n, no_res;
public int max[][]=new int[10][10];
public int allot[][]=new int[10][10];
public int need[][]=new int[10][10];
public Bankers(int n, int res)
{
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
this.n=n;
no_res=res;
}
public void read_data()
{
int i,j;

for(i=0;i<n;i++)
{ proc_id[i]=i;
}

try{
DataInputStream in=new DataInputStream(System.in);

System.out.println("Enter available data");

Mm
for(i=0;i<no_res;i++)
avail[i]=Integer.parseInt(in.readLine());

System.out.println("n="+n);
System.out.println("Enter max matrix");
for(i=0;i<n;i++)
for(j=0;j<no_res;j++)
max[i][j]=Integer.parseInt(in.readLine());

System.out.println("Enter allot matrix");


for(i=0;i<n;i++)
for(j=0;j<no_res;j++)
allot[i][j]=Integer.parseInt(in.readLine());

// find need
for(i=0;i<n;i++)
for(j=0;j<no_res;j++)
need[i][j]=max[i][j]-allot[i][j];
}catch(Exception e){}
}

public void print_data()


{
int i,j;

System.out.println("Need ");
System.out.println("-------------------------");
for(i=0;i<n;i++)
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
{ for(j=0;j<no_res;j++)
System.out.print(need[i][j]+" ");
System.out.println();
}
}

public void safety()


{
int i,j,p,k;
System.out.println("inside safety function");
boolean fin[]=new boolean[n+1];
int safeSeq[]=new int[n+1];
int work[]=new int[no_res];

System.out.flush();
for(i=0;i<no_res;i++)
work[i]=avail[i];
for(i=0;i<n;i++)
fin[i]=false;
int count = 0;
while (count <n)
{
boolean found = false;
for (p = 0; p < n; p++)
{
if (fin[p] ==false)
{

for (j = 0; j < no_res; j++)


if (need[p][j] > work[j])
break;

if (j == no_res)
{

for ( k = 0 ; k < no_res ; k++)


work[k] += allot[p][k];

safeSeq[count++] = p;

fin[p] = true;

found = true;
}
}
}

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
if (found == false)
{
System.out.println("System is not in safe state");
return;
}
}

System.out.println("System is in safe state.\nSafe sequence is: ");


for ( i = 0; i < n ; i++)
System.out.print( safeSeq[i]+ " " );
}
}

TEST CASE INPUT OUTPUT STATUS


1. 5
3 7 4 3
1 2 2
332 6 0 0
0 1 1
753 4 3 1
322
902 1 3 4 0 2
222
433

010
200
302
211
002

2.
6 5 7 6 2 1 0 1
0 2 0 1
3 1 1 2 0 1 4 0

1 2 2 2
5 2 3 3
2 1 1 9

4 4 3 2
2 2 5 4
1 3 6 0

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
Viva questions
1 What is time quantum?
2 Explain allocation?
3 Define Buffered Reader?
4 Define DataInputStream?
5 Define InputStreamReader?

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
9. Design, develop and implement a C/C++/Java program to implement page replacement
algorithms LRU and FIFO. Assume suitable input required to demonstrate the results.

File Name: OS_THIRD.java


package OS_THIRD;

import java.io.DataInputStream;

public class OS_THIRD {

public static void main(String[] args)


{
int ch=0;
do{

try{
System.out.println("Menu...");
System.out.println("1... FIFO");
System.out.println("2... LRU");
System.out.println("Enter your choice..:");
DataInputStream in=new DataInputStream(System.in);
ch=Integer.parseInt(in.readLine());
switch(ch)
{
case 1: FIFO fifo=new FIFO(); fifo.read_data(); fifo.find_faults();
break;
case 2: LRU lru=new LRU(); lru.read_data(); lru.find_faults();
break;

}
}catch(Exception e){}
}while(ch<=2&& ch>0);
}
}

Filename: fifo.java
package OS_THIRD;

import java.io.DataInputStream;

public class FIFO {


int no_frames, no_pages;
int frames[]=new int[5];
int pages[]=new int[30];
void read_data()
{
try{
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
System.out.println("enter no. of frames: ");
DataInputStream in=new DataInputStream(System.in);

no_frames=Integer.parseInt(in.readLine());

System.out.println("enter the no of pages ");


no_pages=Integer.parseInt(in.readLine());
System.out.println("enter the page nos ");
for(int j=0;j<no_pages;j++)
pages[j]=Integer.parseInt(in.readLine());

}catch(Exception e){}
}

void find_faults()
{int i=0,page, hit=0, k=0, fault=0,j, l=0;
boolean flag=true;
for( i=0;i<no_frames;i++)

frames[i]=-1;
System.out.println("output....");
print_frames();
do{

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

page=pages[i];

flag=true;
for( j=0;j<no_frames;j++)
{
if(page==frames[j])
{
hit++;
flag=false;
break;
}
}

if(flag) // fault
{

frames[k++]=page;

if(k==no_frames)
k=0;
print_frames();
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
System.out.println();
fault++;
}
else
{
print_frames();

System.out.println();
}

l++;
}
}while(l!=no_pages);

System.out.println("Number of hits="+ hit);


System.out.println("Number of faults="+ fault);
}

void print_frames()
{
System.out.print("frame :");
for( int j=0;j<no_frames;j++)
System.out.print(frames[j]+" ");
}
}

File Name: LRU.java


package OS_THIRD;

import java.io.DataInputStream;
import java.util.ArrayList;
public class LRU {
int no_frames, no_pages;
int frames[]=new int[5];
int pages[]=new int[30];
void read_data()
{
try{
System.out.println("enter no. of frames: ");
DataInputStream in=new DataInputStream(System.in);

no_frames=Integer.parseInt(in.readLine());

System.out.println("enter the no of pages ");


no_pages=Integer.parseInt(in.readLine());
System.out.println("enter the page nos ");
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
for(int j=0;j<no_pages;j++)
pages[j]=Integer.parseInt(in.readLine());

}catch(Exception e){}
}

void find_faults(){

int pointer = 0, hit = 0, fault = 0;


Boolean isFull = false;

ArrayList<Integer> stack = new ArrayList<Integer>();

for(int j = 0; j < no_frames; j++)


frames[j] = -1;

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


{
print_frames();
if(stack.contains(pages[i]))
{
stack.remove(stack.indexOf(pages[i]));
}
stack.add(pages[i]);
int search = -1;
for(int j = 0; j < no_frames; j++)
{
if(frames[j] == pages[i])
{
search = j;
hit++;
break;
}
}
if(search == -1)
{
if(isFull)
{
int min_loc = no_pages;
for(int j = 0; j < no_frames; j++)
{
if(stack.contains(frames[j]))
{
int temp = stack.indexOf(frames[j]);
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
if(temp < min_loc)
{
min_loc = temp;
pointer = j;
}
}
}
}
frames[pointer] = pages[i];
fault++;
pointer++;
if(pointer == no_frames)
{
pointer = 0;
isFull = true;
}
}

print_frames();

System.out.println("The number of Hits: " + hit);

System.out.println("The number of Faults: " + fault);


}

void print_frames()
{
System.out.print("frame :");
for( int j=0;j<no_frames;j++)
System.out.print(frames[j]+" ");
System.out.println();
}
}

TEST CASE INPUT OUTPUT STATUS


1 1
-1 -1 -1
3 1 -1 -1
1 2 -1
4 1 2 3
4 2 3
1
2 0
3
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
4 4

2 2
-1 -1
2 6 -1
4 67
87
6 89
7
8 0
9 4
3 1
-1 -1 -1
3 11 -1 -1
4 11 22 -1
11 22 33
11 44 22 33
22 0
33 4
44
4 2
5 -1 -1 -1 -1 -1
6 7 -1 -1 -1 -1
7 8 -1 -1 -1
7 7 8 9 -1 -1
8 7 8 9 6 -1
9 7 8 9 6 5
6 4 8 9 6 5
5
4 0
6

Viva questions
1 Define FIFO?
2 Define LRU?
3 Write two data structures to implement an LRU Cache?
4 Which of the page replacement algorithms suffers from Belady’s Anomaly ?
5 A memory page containing a heavily used variable that was initialized very early and is in
constant use is removed, then which page replacement algorithm used?

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
10. a) Design, develop and implement a C/C++/Java program to simulate a numerical
calculator

File Name: Calc.java


package OS_FOUR;

public class calc extends javax.swing.JFrame {

boolean flag=false;
double op1, op2,res;
String op;
public calc() {
initComponents();
}

@SuppressWarnings("unchecked")
private void initComponents() {

jPanel1 = new javax.swing.JPanel();


jTextField1 = new javax.swing.JTextField();
jButton2 = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jButton7 = new javax.swing.JButton();
jButton8 = new javax.swing.JButton();
jButton9 = new javax.swing.JButton();
jButton10 = new javax.swing.JButton();
jButton11 = new javax.swing.JButton();
jButton12 = new javax.swing.JButton();
jButton13 = new javax.swing.JButton();
jButton14 = new javax.swing.JButton();
jButton15 = new javax.swing.JButton();
jButton16 = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

jTextField1.setText(jTextField1.getText()+jButton1.getText());

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {


Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
if(flag==false)
jTextField1.setText(jTextField1.getText()+jButton2.getText());
else
{
flag=false;
jTextField1.setText(jButton2.getText());
}
}

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {


if(flag==false)
jTextField1.setText(jTextField1.getText()+jButton3.getText());
else
{
flag=false;
jTextField1.setText(jButton3.getText());
}
}

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {


if(flag==false)
jTextField1.setText(jTextField1.getText()+jButton4.getText());
else
{
flag=false;
jTextField1.setText(jButton4.getText());
}
}

private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {


if(flag==false)
jTextField1.setText(jTextField1.getText()+jButton5.getText());
else
{
flag=false;
jTextField1.setText(jButton5.getText());
}

private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {


if(flag==false)
jTextField1.setText(jTextField1.getText()+jButton6.getText());
else
{
flag=false;
jTextField1.setText(jButton6.getText());
}
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
}

private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {


if(flag==false)
jTextField1.setText(jTextField1.getText()+jButton7.getText());
else
{
flag=false;
jTextField1.setText(jButton7.getText());
}
}

private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {


if(flag==false)
jTextField1.setText(jTextField1.getText()+jButton8.getText());
else
{
flag=false;
jTextField1.setText(jButton8.getText());
}
}

private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {


if(flag==false)
jTextField1.setText(jTextField1.getText()+jButton9.getText());
else
{
flag=false;
jTextField1.setText(jButton9.getText());
}
}

private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {


if(flag==false)
jTextField1.setText(jTextField1.getText()+jButton10.getText());
else
{
flag=false;
jTextField1.setText(jButton10.getText());
}

private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {


op1=Double.parseDouble(jTextField1.getText());
op=jButton11.getText();
jTextField1.setText("");

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
}

private void jButton12ActionPerformed(java.awt.event.ActionEvent evt) {


op1=Double.parseDouble(jTextField1.getText());
op=jButton12.getText();
jTextField1.setText("");
}

private void jButton13ActionPerformed(java.awt.event.ActionEvent evt) {


op1=Double.parseDouble(jTextField1.getText());
op=jButton13.getText();
jTextField1.setText("");
}

private void jButton14ActionPerformed(java.awt.event.ActionEvent evt) {


op1=Double.parseDouble(jTextField1.getText());
op=jButton14.getText();
jTextField1.setText("");
}

private void jButton15ActionPerformed(java.awt.event.ActionEvent evt) {

jTextField1.setText("");
}

private void jButton16ActionPerformed(java.awt.event.ActionEvent evt) {


op2=Double.parseDouble(jTextField1.getText());
switch(op)
{
case "+": res=op1+op2;

jTextField1.setText(String.valueOf((int)res)); flag=true;
break;
case "-": res=op1-op2;

jTextField1.setText(String.valueOf((int)res)); flag=true;
break;
case "*": res=op1*op2;

jTextField1.setText(String.valueOf((int)res)); flag=true;
break;
case "/": if(op2==0)
{
jTextField1.setText("ERROR"); flag=true;}
else
{
res=op1/op2;

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
jTextField1.setText(String.valueOf((int)res)); flag=true;}
break; }
}

// Variables declaration - do not modify


private javax.swing.JButton jButton1;
private javax.swing.JButton jButton10;
private javax.swing.JButton jButton11;
private javax.swing.JButton jButton12;
private javax.swing.JButton jButton13;
private javax.swing.JButton jButton14;
private javax.swing.JButton jButton15;
private javax.swing.JButton jButton16;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JButton jButton7;
private javax.swing.JButton jButton8;
private javax.swing.JButton jButton9;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}

Sample Output:

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
TEST CASE INPUT OUTPUT STATUS
1 2+3= 5
2 8*9+3= 75
3 9/3= 3
4 10+23-20= 13
5 115+10*2= 250

Viva questions
1 Define awt?
2 Define java swing?
3 Explain javax.swing?
4 Define JFrame?
5 Explain parseDouble?

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
10. b) Design, develop and implement a C/C++/Java program to simulate page replacement
technique

File Name: fifo_sim.java


package OS_FOUR;

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
public class fifo_sim extends javax.swing.JFrame {

DefaultTableModel model1;
DefaultTableModel model2 ;
JTable table1;
JTable table2;
JFrame f = new JFrame();
JFrame f2 = new JFrame();

public fifo_sim() {
initComponents();
model1 = new DefaultTableModel();
model2 = new DefaultTableModel();

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

int rowCount = model1.getRowCount();


//Remove rows one by one from the end of the table
for (int i = rowCount - 1; i >= 0; i--) {
model1.removeRow(i);

}
model1.setColumnCount(0);
int rowCount1 = model2.getRowCount();
for (int i = rowCount1 - 1; i >= 0; i--) {
model2.removeRow(i);
}
model2.setColumnCount(0);
table1 = new JTable(model1);
table2 = new JTable(model2);
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
for(int i=1;i<=Integer.parseInt(jTextField1.getText());i++)
{
model1.addColumn(String.valueOf(i));
model2.addColumn(String.valueOf(i));
}

for(int i=0;i<table1.getColumnCount();i++)
{
table1.getColumnModel().getColumn(i).setPreferredWidth(29);
table2.getColumnModel().getColumn(i).setPreferredWidth(29);
}
Object o[]= new Object[table1.getColumnCount()];
for(int i=0;i<table1.getColumnCount();i++)
o[i]="";

model1.addRow(o);
for(int i=1;i<=Integer.parseInt(jTextField2.getText())+2;i++)
model2.addRow(o);

table1.setBorder(null);
table2.setBorder(null);
JScrollPane js =new JScrollPane(table1);
js.setPreferredSize(null);
js.setBorder(null);
js.setViewportBorder(null);

f.setLocation(50,250);
f.setUndecorated(true);
f.setSize(800,200);
f.add(js);
f.setVisible(true);
table1.setTableHeader(null);
table1.setBorder(null);

JScrollPane js2 =new JScrollPane(table2);


js2.setPreferredSize(null);
js2.setBorder(null);
js2.setViewportBorder(null);
f2.setLocation(50,450);
f2.setUndecorated(true);
f2.setSize(800,200);
f2.add(js2);
f2.setVisible(true);
table2.setTableHeader(null);
table2.setBorder(null);
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {


f.setVisible(true);
f2.setVisible(true);
int nof=Integer.parseInt(jTextField2.getText());
int nop=Integer.parseInt(jTextField1.getText());
Object page;

boolean flag=true;
int l=0,j,i;
int k=0, hit=0, fault=0;
flag=true;

do
{

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

if(i>0)
{
for(int j1=0;j1<nof;j1++)
table2.setValueAt(table2.getValueAt(j1, i-1),j1,i);
}
page=table1.getValueAt(0,i);
flag=true;

for(j=0;j<nof;j++)
{
if(page.equals(table2.getValueAt(j,i)))
{
hit++;

flag=false;
//---

//--
break;
}
}

if(flag) // fault
{

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
table2.setValueAt(page,k++ , i);
table2.setValueAt("F", nof+1, i);

fault++;
if(k==nof)
k=0;
}
l++;

}
}while(l<nop);

jTextField3.setText(String.valueOf(fault));
jTextField4.setText(String.valueOf(hit));
}

// Variables declaration - do not modify


private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
}

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
Sample Output

Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE

You might also like