Professional Documents
Culture Documents
SS 0slab 15csl67
SS 0slab 15csl67
SS 0slab 15csl67
15CSL67
SYSTEM SOFTWARE AND OPERATING SYSTEM LABORATORY
[As per Choice Based Credit System (CBCS) scheme]
MANUAL
PREPARED BY
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
HKBK COLLEGE OF ENGINEERING
Nagawara, Bangalore -560 045
www.hkbkeducation.org
Programme Outcomes:
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.
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.
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);
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; }
;
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;
}
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");
}
}
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");
}
}
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;
}
}
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;
}
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 name1This statement changes the start condition to name1
BEGIN INTIAL or BEGIN 0This 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
argcno 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** argvpointer 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;
}
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);
}
}
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{
System.out.println(proc[i].pid+"\t"+proc[i].bt+"\t"+proc[i].art);
}
System.out.println("Quantum : "+ q);
}
rem_bt[i] = proc[i].bt;
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
while(true)
{
boolean done = true;
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;
}
}
}
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.InputStreamReader;
bt= bufferedReader.readLine();
at= bufferedReader.readLine();
proc[i]=new Process(i+1,Integer.parseInt(bt),Integer.parseInt(at));
}
}catch(Exception e){}
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);
System.out.println("Processes " +
" Burst time " +
" Waiting time " +
" Turn around time");
while (complete != n) {
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++;
}
}
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
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.InputStreamReader;
}catch(Exception e){}
}
}
package OS_SECOND;
import java.io.DataInputStream;
for(i=0;i<n;i++)
{ proc_id[i]=i;
}
try{
DataInputStream in=new DataInputStream(System.in);
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());
// 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){}
}
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();
}
}
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)
{
if (j == no_res)
{
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;
}
}
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.
import java.io.DataInputStream;
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;
no_frames=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);
void print_frames()
{
System.out.print("frame :");
for( int j=0;j<no_frames;j++)
System.out.print(frames[j]+" ");
}
}
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());
}catch(Exception e){}
}
void find_faults(){
print_frames();
void print_frames()
{
System.out.print("frame :");
for( int j=0;j<no_frames;j++)
System.out.print(frames[j]+" ");
System.out.println();
}
}
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
boolean flag=false;
double op1, op2,res;
String op;
public calc() {
initComponents();
}
@SuppressWarnings("unchecked")
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextField1.setText(jTextField1.getText()+jButton1.getText());
Smitha Kurian, Tabassum Ara , Manjula HT & Rashmi Purad Dept. of CSE @ HKBKCE
}
jTextField1.setText("");
}
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; }
}
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
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();
}
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);
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));
}
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