You are on page 1of 28

1) State and explain about what an operating system is?

Operating system is made up of basically two functions they are managing resourc
es and extending the machine. Operating system gives a user interface through wh
ich he can perform various functions. It acts as a medium for communication betw
een the machine and user.
2) Explain about what a signal is?
A signal is a software mechanism that informs a process of the occurrence of asy
nchronous events. It does not employ priorities but it is more or less similar t
o a hardware interrupt. That is, all signals are treated equally. Signals that o
ccur at the same time are presented to a process one at a time, with no particul
ar ordering.
3) What design and management issues are raised by the existence of concurrency?
The operating system must be able to keep track of the various active processes.
The operating system must allocate and de-allocate various resources for each ac
tive process.
The operating system must protect the data and physical resources of each proces
s against unintended interference by other processes. This involves techniques t
hat relate to memory, files, and I/O devices.
The results of a process must be independent of the speed at which the execution
is carried out relative to the speed of other concurrent process.
4) What are the contexts in which concurrency may occur?
Concurrency may arise in three different contexts.
Multiple applications: -Processing time of the computer to be dynamically shared
among a number of active jobs or applications
Structured application: - With principles of modular design and structured progr
amming some applications can be effectively implemented as a set of concurrent p
rocess.
Operating system structure: -The same structuring advantages apply to the system
programmer.
5) What is a data register and address register?
Data registers can be assigned to a variety of functions by the programmer. They
can be used with any machine instruction that performs operations on data.
Address registers contain main memory addresses of data and instructions or they
contain a portion of the address that is used in the calculation of the complet
e addresses.
6) What are server operating systems?
These run on servers, which are very large personal computers, work stations, or
even mainframes. They serve multiple users at once over a network and allow the
users to share hardware and software resources. Server O.S. provide various fun
ctions such as file and print service, or web service. Typical server operating
systems are UNIX and Windows 2000.
7) Describe system calls for file management?
To make changes a file must be opened. This call specifies the file name to be o
pened, either as an absolute path name or relative to the working directory, and
a code of O_RDONLY, O_WRONLY or O_RDWR, meaning open for reading, writing or bo
th. The file descriptor can then be used for reading or writing.
8) Describe about MULTICS?
MULTICS is described as having a series of concentric rings, with the inner ones
being more privileged than the outer ones. When a procedure in an outer ring wa
nted to call a procedure in an inner ring, it had to make the equivalent of a sy
stem call which is a TRAP instruction. MULTICS hardware made it possible to desi
gnate individual process as protected against reading, writing, or executing.

9) Describe about threads?


Different threads in a process are not quite as independent as different process
. All threads share the same global variables as they have the same address spac
e. One thread can read, write, or even completely wipe out another threads stack
.
10) Describe the mechanism of upcall?
When the kernel knows that a thread has blocked, the kernel notifies the process
es run time system, passing as parameters on the stack the number of the thread
in question and a description of the event that occurred. The notification happe
ns by having the kernel activate the run-time system at a known starting address
, roughly analogous to a signal in UNIX.
11) Give an example of page replacement in the areas of computer design?
Majority of the computers have more than one memory caches consisting of 32-byte
or 64-byte blocks of memory. Whenever a cache is full then some part of the blo
ck should be chosen for removal. This problem is precisely the same page replace
ment except on a shorter time scale.
12) Describe about preemptive scheduling algorithm?
A preemptive scheduling algorithm picks a process and lets it run
of some fixed time. If it is still running at the end of the time
s suspended and the scheduler picks another process to run. Doing
eduling requires having a clock interrupt occur at the end of the
to give control of the CPU back to the scheduler.

for a maximum
interval, it i
preemptive sch
time interval

13) Give a case situation where a scheduling is needed?


When an interrupt occurs, a scheduling decision may be made. If the interrupt ca
me from an I/O device that has now completed its work, some process that was blo
cked waiting for the I/O may now be ready to run. It is up to the scheduler to d
ecide if the newly ready process should run or not.
14) Describe about checkpointing?
Checkpointing a process means that its state is written to a file so that it can
be restarted later. The checkpoint contains not only the memory image, but also
the resource state, that is, which resources are currently assigned to the proc
ess. To be most effective, new checkpoints should not overwrite old ones but sho
uld be written to new files. Whole sequences of checkpoint files are accumulated
due to the process getting executed.
15) Describe the two phases of two-phase locking?
In the first phase, the process tries to lock all the records it needs, one at a
time. If it succeeds, it begins the second phase, performing its updates and re
leasing the locks. No real work is done in the first phase.
16) Explain about deadlocks in operating systems?
Deadlock is a potential problem in any operating system. It occurs when a group
of processes each have been granted exclusive access to some resources, and each
one wants yet another resource that belongs to another process in the group. Al
l of then are blocked and non will ever run again.
17) Explain about the paging systems?
Paging systems can be modeled by abstracting the page reference string from the
program and using the same reference string with different algorithms. These mod
els can be used to make some predictions about paging behavior. Attention to iss
ues such as determining the working set, memory allocations, and page size are r
equired.
==================================================
1)
Explain lex and yacc tools:-

Lex:- scanner that can identify those tokens


Yacc:- parser.yacc takes a concise description of a grammar and produces a C rou
tine that can parse that grammar.
2)

give the structure of the lex program:definition section- any intitial c program code
% %
Rules section- pattern and action separated by white space
%%
User subroutines section-concsit of any legal code.

3)
The lexer produced by lex in a c routine is called yylex()
4)
Explain yytext:- contains the text that matched the pattern.
5)
The yacc produced by parser is called yyparse().
6)
Why we have to include y.tab.h in lex?
y.tab.h contains token definitions eg:- #define letter 258.
7) explain the structure of a yacc program?
Defn section- declarations of the tokens used in the grammar
%%
The rules section-pattern action
%%
Users subroutines section
8)
explain yyleng?
Yyleng-contains the length of the string our lexer recognizes.
9)
features of unix:-multitasking,mutiuser,online help facility,security,fi
le & process.
10) What is an internal command?give an example?
Command which is shell built-in eg:echo
11) what is an external command?give a example?
Command which resides in other directories-eg:cd in /bin
12) what is an absolute path name?give an example?
A file name identification with respect to the root. Eg:- /home/kumar/f1
13) what is an relative path name?
A file identification not with respect to the root.
13) differentiate the commands cp and mv?
Cp- copy the files
mv- renaming the file.
14) explain mkdir command?
Used to create a directory
Eg:mkdir m1,m2
15) what are tokens or terminal symbols?
Symbols that appear in the input are returned by the lexer are terminal symbols.
16) what type of data structures is used by shift/reduce parsing?
Stack.
17) shell- it is a command interpreter
kernel- is the core of the operating system.
18) what is lexical analyzer?
Lex taking a set of descriptions of possible tokensand producing a C routine is ca
lled a lexical analyzer (or) lexer (or) scanner.
19) define grammer?
The list of rules that define the relationship that the program understands i
s a grammar.
20) what is symbol table?
The table of words is a simple symbol table,a common structure in lex and yac

c applications.
=========================================================
Important questions:
1. Discuss about os objectives and functions
2. Explain about os structures with neat figures
3. Briefly discuss about os services
4. What are different schedulers? Explain about scheduling criteria
5. Explain round robin and priority scheduling algorithms with any example
6. Discuss about critical section problem and provide Petersons solution semapho
res.
7. What is the differncebetween binary and counting semaphores and how they prov
ide solution for critical section?
8. Explain about readers writers problem with code
9. What is dining philosopher s problem and how can we provide solution without ge
tting deadlock.
10. Clearly explain bankers algorithm for deadlock avoidance
11. What are conditions for occurring deadlocks how can we prevent them
12. Explain about Disk scheduling algorithms with an example
13. Discuss various allocation methods on files
14. Draw hardisk structure and discuss various parts
15. Differentiate between internal and external fragmentation problem with figur
es
16. What are fixed and variable partitioning schemes
17. Implement LRU and optimal page replacement algorithms with any example
18. Explain about Direct memory access with a neat figure
19. What is blocking I/O and non blocking I/O
20. Discuss about various security attacks and threats
21. What are different viruses and how can we protect our system from viruses
22. Discuss about FCFS and SJF scheduling algorithms with an example
23. Explain about paging concept with a neat figure
24. how address translation is done from logical memory to physical memory in se
gmentation
=================================================
INTRODUCTION
LEX
Lex is a program designed to generate scanners, also known as tokenizers, which
recognize lexical patterns in text. It helps in writing programs whose control f
low is directed by instances of regular expression in the input stream.
Lex is a tool for automatically generating a lexer or scanner given a lex specif
ication ( .l file )
A Lexer or Scanner is used to perform lexical analysis, or the breaking up of an
input stream into meaningful units, or tokens. For example, consider breaking a
text file up into individual words.
Skeleton of a Lex Specification ( .l file)
The Rules Section :
%%
[RULES SECTION]
<pattern>
{ <action to take when matched> }
<pattern>
{ <action to take when matched> }
%%

Patterns are specified by regular expressions.


For example:
%%
[A-Za-z]*
{ printf( this is a word ); }
%%
Regular Expression Basics:
. :
* :
+ :
? :
| :
[ ] :
() :
:

matches any single character except \n


matches 0 or more instances of the preceding regular expression
matches 1 or more instances of the preceding regular expression
matches 0 or 1 of the preceding regular expression
matches the preceding or following regular expression
defines a character class
groups enclosed regular expression into a new regular expression
matches everything within the
literally

Lex Regular Expression :


x|y
{i}
x/y
x{m,n}
x
x$
"s"

x or y
definition of i
x, only if followed by y (y not removed from input)
m to n occurrences of x
x, but only at beginning of line
x, but only at end of line
exactly what is in the quotes (except for "\" and
following character)

A regular expression finishes with a space, tab or newline


Regular Expression Examples:
an integer: 12345
[1-9][0-9]*
a word: cat
[a-zA-Z]+
a (possibly) signed integer: 12345 or -12345
[-+]?[1-9][0-9]*
a floating point number: 1.2345
[0-9]* . [0-9]+
a delimiter for an English sentence
. | ? | ! OR
[ . ? !]
C++ comment: // call foo() here!!
// .*
white space
[ \t]+
English sentence: Look at this!
([ \t]+|[a-zA-Z]+)+( . | ? |!)
Special Functions:
yytext
Where text matched most recently is stored
yyleng
Number of characters in text most recently matched
yylval
Associated value of current token
yymore()
Append next string matched to current contents of yytext
yyless(n)
Remove from yytext all but the first n characters

unput(c)
Return character c to input stream
yywrap()
May be replaced by user
The yywrap method is called by the lexical analyzer whenever it inputs an EOF as
the first character when trying to match a regular expression
Compiling commands
lex file.l
cc lex.yy.c

ll

./a.out

Yacc:
A tool for automatically generating a parser given a grammar written in a yacc s
pecification (.y file)
A grammar specifies a set of production rules, which define a language. A produc
tion rule specifies a sequence of symbols, sentences, which are legal in the lan
guage.
Structure of yacc File
Definition section
Declarations of tokens
Type of values used on parser stack
Rules section
List of grammar rules with semantic routines
User code
Skeleton of a yacc specification (.y file)
The Production Rules Section
%%
production : symbol1 symbol2
{ action }
| symbol3 symbol4
{ action }
|

production: symbol1 symbol2


%%
An example

{ action }

Defining Values:
expr :
|
;
term :
|
;
factor

expr '+' term


term

{ $$ = $1 + $3; }
{ $$ = $1; }

term '*' factor { $$ = $1 * $3; }


factor
{ $$ = $1; }
: '(' expr ')'
| ID
| NUM
;

{ $$ = $2; }

Example
Scanner .l file
%{
#include
#include
%}
id
wspc
semi
comma
%%
int
char
float
{comma}
{semi}
{id}
{wspc}

<stdio.h>
"y.tab.h"
[_a-zA-Z][_a-zA-Z0-9]*
[ \t\n]+
[;]
[,]
{ return
{ return
{ return
{ return
{ return
{ return
{;}

INT; }
CHAR; }
FLOAT; }
COMMA; }
SEMI; }
ID;}

/* Necessary? */

.y file
%{
#include <stdio.h>
#include <stdlib.h>
%}
%start line
%token CHAR, COMMA, FLOAT, ID, INT, SEMI
%%
Compiling Commands
Yacc filename.y

cc yy.tab.c
./a.out
============================
COMPILER DESIGN :
A Compiler is a program takes a program written in a source language
and translates it into an equivalent program in a target language
Source Program
(Generally written in a
High level language)

Compiler

Target Program

Error Messages
Major Parts of Compilers :
There are two major parts of a compiler: Analysis and Synthesis
In analysis phase, an intermediate representation is created from the given sou
rce program.
-- Lexical Analyzer, Syntax Analyzer and Semantic Analyzer are the parts of this
phase.
In synthesis phase, the equivalent target program is created from this intermed
iate representation.
-- Intermediate Code Generator, Code Generator, and Code Optimizer are the parts
of this phase.
Phases of a Compiler
Source
Code
e Generator

Lexical
Semantic
Target Progrm
Analyzer
Optimizer
Program

Intermediate
Analyzer

Cod

Each phase transforms the source program from one representation


into another representation.

They communicate with error handlers.

They communicate with the symbol table.

Intermediate Code Generation


A compiler may produce an explicit intermediate codes representing the source
program.
These intermediate codes are generally machine (architecture independent). But
the level of intermediate codes is close to the level of machine codes.
Ex:
newval := oldval * fact + 1
id1 := id2 * id3 + 1
MULT id2, id3,temp1
ADD
temp1,#1,temp2
MOV
temp2,,id1
Code Generator

Produces the target language in a specific architecture.


The target program is normally is a relocatable object file containing the mach
ine codes.
Ex: ( assume that we have an architecture with instructions whose at least one
of its operands is a machine register)
MOVE
MULT
ADD
MOVE

id2,R1
id3,R1
#1,R1
R1,id1

Compiling Commands
cc pgmname.c
./a.out

PART-A
LEX Programs
1a) Program to count number of characters, words, spaces and lines in a given i
nput file
%{
#include<stdio.h>
int c=0;

int
int
int
int
%}

w=0;
b=0;
l=0;
t=0;

Word [^ \t\n]+
EOL \n
%%
{Word} { w++; c=c+yyleng; }
{EOL} { l++; c++; }
[ ] { b++; c++;}
[\t] { t++;c=c+4; }
%%
main(int argc,char *argv[])
{
if(argc==2)
{
yyin=fopen(argv[1],""r);
if(!yyin)
{
printf("Could not open %s file \n",argv[1]);
exit(0);
}
yylex();
fclose(yyin);
printf("------------------------------------------------\n");
printf("Number of Lines =%d \n",l);
printf("Number of Words = %d\n",w);
printf("Number of tab spaces =%d\n",t);
printf("Number of white spaces =%d \n",b);
printf("Number of charaters =%d\n ",c);
printf("--------------------------------------------------\n");
}
else
printf("Usage : %s <srcfile>\n",argv[0]);
}

1.b) Program to count the number of comment lines in a given C program. Also eli
minate them and copy that file into another file
%{
int c=0;
%}
%%
("/*")((.)*|\n)*("*/") c++;
("//")(.)* c++;
. ECHO;
%%
main(int argc ,char *argv[])
{
if(argc<3)
{
printf("Usage:%s <srcfile> <destfile> \n",argv[0]);
exit(0);
}
yyin=fopen(argv[1],"r");

if(!yyin)
{
printf("Error in opening the file 0\n");
exit(0);
}
yyout=fopen(argv[2],"w");
yylex();
fclose(yyin);
fclose(yyout);
printf("---------------------------------------------------------------\n");
printf("The number of comment lines present in the source file =%d \n",c);
printf("---------------------------------------------------------------\n");
return 0;
}

2.a) Program to recognize a valid arithmetic expression and identify the identif
iers and operators present. Print them separately.
/*valid arithmetic expression*/
%{
int id=0;
int numid=0;
int op=0;
int valid=1;
int p=0;
%}
%%
\( {
if(id==0)
{
p++;
}
else
valid=0;
}
\) {
if(id && valid)
{
p--;
}
else
valid=0;

}
[a-zA-Z0-9]+ {
if(!id && valid)
{
id=1;
numid++;
printf("identifier=%s\n",yytext);
}
else
valid=0;
}
[-+*/] {
if(id && valid)
{
id=0;
op++;
printf("operator =%s\n",yytext);
}
else
valid=0;
}
%%
main()
{
printf("Enter the expression");
yylex();
if(p==0 && op==numid-1 && valid==1)
{
printf("Valid arithmetic exp");
printf("Number of identifier =%d\n",numid);
printf("Number of operator =%d\n",op);
}
else
printf("Invalid arithmatic exp\n");
}

2. b) Program to recognize whether a given sentence is simple or compound


/*simple or compound sentence*/
%{
int vsim=0;
int vcom=0;
%}
semi [;]
ob [{]
cb [}]
any [^{}]+
%%
{any}{semi} { vsim=1;}
{any}{ob}{any}*{cb}{semi}* {vcom=1;}
%%
main()
{
printf("ENTER THE STATEMENT\n");
yylex();
if(vcom)
{
printf("COMPOUND STATEMENT\n");
}
if(vsim)
{
printf("SIMPLE STATEMENT\n");
}
else
printf("invalid statement\n");
}
OR
/*simple or compound sentence*/
%{
%}
%%
[ ][Aa][Nn][Dd][ ] |
[ ][oO][rR][ ] |
[ ][bB][uU][Tt][ ] |
[ ][Nn][eE][vV][eE][rR][tT][hH][lL][eE][sS]+[ ] |
[ ][bB][eE][cC][aA][uU][sS][eE][ ] { printf("Compound sentance\n");exit(0); }
. ;
%%
main()
{

printf(" Enter a statement \n");


yylex();
printf("Simple sentance \n");
}
}

3) Program to recognize and count the number of identifiers of a given input fil
e
%{
#include<stdio.h>
int count=0;
char srcfl[100];
%}
letter [a-zA-Z_]+
digit [0-9]*
id {letter}*|({letter}{digit})+
notid ({digit}{letter})+|{digit}*
arr ("["[0-9]*"]")
fun [();]
%%
[\t\n]+
("int") |
("void") |
("char") |
("float") |
("double") { printf("%s is a keyword\n", yytext); }
{id}{fun}*{arr}* { printf("%s is a identifier\n", yytext); count++; }
{notid} { printf("%s not an identifier\n", yytext); }
. ;
%%
int main(int argc, char *argv[])
{
if(argc>1)
{
yyin=fopen(argv[1],"r");
}
else
{
printf("enter the src file name\n");
scanf("%s",srcfl);
yyin=fopen(srcfl,"r");
}
yylex();
printf("identifier count is %d",count);
return 0;
}

YACC
4. a) Program to recognize a valid arithmetic expression that uses operators +,,*, and
YACC part
%{
#include <stdio.h>
%}
%left '+' '-'
%left '*' '/'
%token ID
%%
lines:
| lines e
| lines '\n'
e:

e '+' e
| e '-' e
|
|
|
|

e '*' e
e '/' e
'(' e ')'
ID

%%

int main()
{
printf ("This Yacc program validates a given math expression.");
printf ("\nEnter the expression and terminate with ENTER key:\n");
if (!yyparse())
printf ("Valid expression.\n");
return 0;
}
int yyerror()
{
printf ("Invalid expression.\n");
return 1;
}
int yylex()
{
int c;
c = getchar();
if (c == '\n')
return 0;
if (isalnum(c))
return ID;

return c;
}

4. b) Program to recognize a valid variable, which starts with a letter, followe


d by any number of letters or digits.
%{
#include <stdio.h>
#include <ctype.h>
%}
%token DIGIT ALPHA
%%
line:
var:

'\n'

;
| var '\n' { printf ("Valid identifier.\n"); return; }
ALPHA

| var alphanum
alphanum:

DIGIT
| ALPHA

%%
int main()
{
printf ("This Yacc program validates a C identifier.");
printf ("\nEnter the variable:\n");
yyparse();
}
int yylex()
{
char c;
c = getchar();
if (isdigit (c))
return DIGIT;
else if (isalpha (c) || c == '_')
return ALPHA;
return c;
}
int yyerror()
{
printf ("Invalid identifier.\n");
}

5. a) Program to evaluate an arithmetic expression involving operators +,-,* an


d /
%{
#include <stdio.h>
#define YYSTYPE double
%}
%token NUMBER
%left '+' '-'
%left '*' '/'
%%
start:
| start expr '\n' { printf ("Value: %f\n", $2); return 0; }
| start '\n'
expr:

expr '+' expr


|
|
|
|
|

{ $$ =
expr '-'
expr '*'
expr '/'
'(' expr
NUMBER

$1 +
expr
expr
expr
')'

$3; }
{ $$ =
{ $$ =
{ $$ =
{ $$ =

$1 - $3; }
$1 * $3; }
$1 / $3; }
$2; }
{ $$ = $1; }

%%
main()
{
printf ("This Yacc program evaluates a math expression.\n");
printf ("Enter the expression:\n");
yyparse();
}
yylex()
{
char c;
while ((c=getchar()) == ' ')
;
if (isdigit(c)) {
ungetc (c, stdin);
scanf ("%lf", &yylval);
return NUMBER;
}
return c;
}
yyerror()
{
printf ("Expression invalid.\n");
}
5. b) Program to recognize strings
%token A

aaab , abbb , ab and

using grammer (anbn,n>0)

%%
start:
| A start B
%%
yyerror()
{
printf ("String unacceptable for the grammar (a^n)(b^n).\n");
exit (1);
}
yylex()
{
char c;
c = getchar();
if (c == 'a') return A;
if (c == 'b') return B;
if (c == '\n') return 0;
return c;
}
main()
{
printf ("This Yacc program checks if a string can");
printf (" be accepted by the grammar (a^n)(b^n).\n");

printf ("Enter a string to check:\n");


yyparse();
printf ("String acceptable for the grammar (a^n)(b^n).\n");
}

6) Program to recognize the grammar (anbn, n>=10)


%{
%}
%token A B
%%
LINE : A A A A A A A A A A START B'\n' { printf("Accepted \n");exit;}
START :
| A START
;
%%
#include<stdio.h>
#include<ctype.h>
Main()
{
Printf("Enter the grammer \n");
Yyparse();
}
Yylex()
{
Int c;
C=getchar();
If(c==EOF) return 0;
If(c=='a') return A;
If(c=='b') return B;
Return c;
}
Yyerror()
{
Printf("Not accpted \n");
}
COMPILER DESIGN
5. Write a C program to implement the syntax-directed definition of
nd if E then S1 else S2 .

if E then S1 a

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int parsecondition(char[],int ,char *,int);
void gen(char[],char[],char[],int);
int main()
{
int counter=0,stlen=0,elseflag=0;
char stmt[60];
char strB[54];
char strS1[50];
char strS2[45];
printf("format of if statement\n example............\n");
printf("if(a<b)then(s,a);\n");
printf("if(a<b)then(s,a) else (s,b);\n\n");
printf("enter the statement\n");
scanf("%s",&stmt);
stlen=strlen(stmt);
counter=counter+2;
counter=parsecondition(stmt,counter,strB,stlen);
if(stmt[counter]==')')
counter++;
counter=counter+3;
counter=parsecondition(stmt,counter,strS1,stlen);
if(stmt[counter+1]==';')
{
printf("\n parsing the input statement...\n");
gen(strB,strS1,strS2,elseflag);
return 0;
}
if(stmt[counter]==')')
counter++;
counter=counter+3;
counter=parsecondition(stmt,counter,strS2,stlen);
counter=counter+2;
if(counter==stlen)
{
elseflag=1;
printf("\n parsing the input statement");
gen(strB,strS1,strS2,elseflag);
return 0;
}
return 0;
}
int parsecondition(char input[],int cntr , char *dest, int totallen)
{
int index=0,pos=0;
while(input[cntr]!='(' && cntr<=totallen)
cntr++;
if(cntr>=totallen)
return 0;
index=cntr;
while(input[cntr]!=')')
cntr++;
if(cntr>=totallen)
return 0;
while(index<=cntr)
dest[pos++]=input[index++];

dest[pos]='\0';
return cntr;
}
void gen(char B[],char S1[],char S2[],int elsepart)
{
int Bt=101,Bf=102,Sn=103;
printf("\n\t if %s goto %d",B,Bt);
printf("\n\t goto %d",Bf);
printf("\n %d:",Bt);
printf("%s",S1);
if(!elsepart)
printf("\n %d:",Bf);
else
{
printf("\n\t goto %d",Sn);
printf("\n %d : %s",Bf,S2);
printf("\n %d:",Sn);
}
}

6. Write a yacc program that accepts a regular expression as input and produce i
ts parse tree
%{
#include<ctype.h>
char str[20];
int i=0;
%}
%token id
%left '+''/''*''-'
%%
E:S {infix_postfix(str);}
S:S'+'T|S'-'T
|T
T:T'*'F|T'/'F
|F
F:id|'('S')'
;
%%
#include<stdio.h>
main()

{
printf("\n Enter the grammar:");
yyparse();
}
yyerror()
{
printf("invalid");
}
yylex()
{
char ch=' ';
while(ch!='\n')
{
ch=getchar();
str[i++]=ch;
if(isalpha(ch)) return id;
if(ch=='+'||ch=='*'||ch=='-'||ch=='/') return ch;}
str[--i]='\0';
return(0);
exit(0);
}
void push(char stack[],int *top, char ch)
{
stack[++(*top)]=ch;
}
char pop(char stack[],int *top)
{
return(stack[(*top)--]);
}
int prec(char ch)
{
switch(ch)
{
case '/' :
case '*' : return 2;
case '+' :
case '-' : return 1;
case '(' : return 0;
default : return -1;
}
}
void infix_postfix(char infix[])
{
int top=-1,iptr=-1,pptr=-1;
char postfix[20],stack[20],stksymb,cursymb;
push(stack,&top,'\0');
while((cursymb=infix[++iptr])!='\0')
{
switch(cursymb)
{
case '(' : push(stack,&top,cursymb);
break;
case ')' : stksymb=pop(stack,&top);
while(stksymb!='(')
{
postfix[++pptr]=stksymb;
stksymb=pop(stack,&top);
}
break;

case
case
case
case

'*'
'/'
'+'
'-'

:
:
:
: while (prec(stack[top])>=prec(cursymb))
postfix[++pptr]=pop(stack,&top);
push(stack,&top,cursymb);
break;
default : if(isalnum(cursymb)==0)
{
printf("error in input:");
exit(0);
}
postfix[++pptr]=cursymb;
}
}
while(top!=-1)
postfix[++pptr]=pop(stack,&top);
printf("%s\n",postfix);
}
Viva Questions
System Software
1.
What is a System?
Systems have interconnectivity; the various parts of a system have functional as
well as structural relationships to each other.
2.
What is System software?
System software is computer software designed to operate the computer hardware a
nd to provide a platform for running application software.
3.
Difference between System software and application software.

System software gets installed when the operating system is installed on


the computer while application software is installed according to the requiremen
ts of the user.

System software includes programs such as compilers, debuggers, drivers,


assemblers while application software includes media players, word processors, a
nd spreadsheet programs.

Generally, users do not interact with system software as it works in the


background whereas users interact with application software while doing differen
t activities.

A computer may not require more than one type of system software while th
ere may be a number of application software programs installed on the computer a
t the same time.

System software can run independently of the application software while a


pplication software cannot run without the presence of the system software.
4.
What is an Assembler?
Assembler for an assembly language, a computer program to translate between lowe
r-level representations of computer programs.
OR
An assembler converts basic computer instructions into a pattern of bits which c
an be easily understood by the computer and the processor can use it to perform
its basic operations.
5.
What is an editor?
Text editors are often provided with operating systems or software development p
ackages, and can be used to change configuration files and language source.
6.

What is a linker?

Linker (computing), a computer program that takes one or more objects generated
by a compiler and combines them into a single executable program.
7.
What is a compiler?
A compiler is a computer program (or set of programs) that transforms source cod
e written in a programming language (the source language) into another computer
language (the target language, often having a binary form known as object code).
The most common reason for wanting to transform source code is to create an exe
cutable program.
8.
What is a Loader?
A loader is the part of an operating system that is responsible for loading prog
rams. Loading a program involves reading the contents of executable file, the fi
le containing the program text, into memory, and then carrying out other require
d preparatory tasks to prepare the executable for running.
9.
What is a Debugger?
A debugger or debugging tool is a program that is used to test and debug other p
rograms (the "target" program).
10. What is a Interpreter?
An interpreter normally means a computer program that executes, i.e. performs, i
nstructions written in a programming language. An interpreter may be a program t
hat either executes the source code directly and translates source code into som
e efficient intermediate representation (code) and immediately executes.

Lex and Yacc


11. Explain lex and yacc tools:Lex: - scanner that can identify those tokens
Yacc: - parser.yacc takes a concise description of a grammar and produces a C ro
utine that can parse that grammar.

12. Give the structure of the lex program:Definition section- any intitial c program code
% %
Rules section- pattern and action separated by white space
%%
User subroutines section-concsit of any legal code.
13. The lexer produced by lex in a c

routine is called yylex()

14. Explain yytext:- contains the text that matched the pattern.
15. The yacc produced by parser is called yyparse().
16. Why we have to include y.tab.h in lex?
Y.tab.h contains token definitions eg:- #define letter 258.
17. Explain the structure of a yacc program?
Defn section- declarations of the tokens used in the grammar
%%
The rules section-pattern action
%%
Users subroutines section
18. Explain yyleng?
Yyleng-contains the length of the string our lexer recognizes.
19. Define action?
The C code associated with a lex pattern or a yacc rule. When the pattern or rul
e matches an input sequence, the action code is executed.
20. Define Pattern?
In a lex lexer, a regular expression that the lexer matches against the input.
21. What is an Alphabet?
A set of distinct symbols .For example, the ASCII character set is a collection
of 128 different symbols. In a lex specification, the alphabet is the native cha
racter set of the computer, unless you use %T to define a custom alphabet.
22. Define ASCII?
American Standard Code for Information Interchange, a collection of 128 symbols
representing the common symbols found in the American alphabet: lower and upper
case letters, digits and punctuation, plus additional characters for formatting
and control of data communication links.

23. What is an Ambiguity?


An Ambiguous grammar is one with more than one rule or set of rules that match t
he same input.
24. Define Finite Automaton?
An abstract machine which consists of a finite number if instructions. Finite au
tomata are useful in modeling many commonly occurring computer processes and hav
e useful mathematical properties.
25. Define Input.
A stream of data read by a program. For instance, the input to a lex scanner is
a sequence of bytes, while the input to a yacc parser is a sequence of tokens.
26. Define Language.

A well-defined set of strings over some alphabet; informally, some set of instru
ctions for describing tasks which can be executed by a computer.
27. Define Precedence.
The order in which some particular operation is performed.
28. What is a Parser?
A Parser for a Grammar is a program which takes in the Language string as it's i
nput and produces either a corresponding Parse tree or an Error.
29. What is the Syntax of a Language?
The Rules which tells whether a string is a valid Program or not are call
ed the Syntax.
30. What is the Semantics of a Language?
The Rules which gives meaning to programs are called the Semantics of a l
anguage.
31. What are tokens?
When a string representing a program is broken into sequence of substrings, such
that each substring represents a constant, identifier, operator, keyword etc of
the language, these substrings are called the tokens of the Language.
32. What is the Lexical Analysis?
The Function of a lexical Analyzer is to read the input stream representing the
Source program, one character at a time and to translate it into valid tokens.
33. How can we represent a token in a language?
The Tokens in a Language are represented by a set of Regular Expressions. A reg
ular expression specifies a set of strings to be matched. It contains text chara
cters and operator characters. The Advantage of using regular expression is that
a recognizer can be automatically generated.
34. How are the tokens recognized?
The tokens which are represented by an Regular Expressions are recognized in an
input string by means of a state transition Diagram and Finite Automata.

35. Are Lexical Analysis and Parsing two different Passes?


These two can form two different passes of a Parser. The Lexical analysis can st
ore all the recognized tokens in an intermediate file and give it to the Parser
as an input. However it is more convenient to have the lexical Analyzer as a co
-routine or a subroutine which the Parser calls whenever it requires a token.
36. What are the Advantages of using Context-Free grammars ?
It is precise and easy to understand.
It is easier to determine syntactic ambiguities and conflicts in the grammar.
37. What are Terminals and non-Terminals in a grammar?
Terminals:- All the basic symbols or tokens of which the language is composed o
f are called Terminals. In a Parse Tree the Leafs represents the Terminal Symbo
l.
Non-Terminals:- These are syntactic variables in the grammar which r
epresents a set of strings the grammar is composed of. In a Parse tree all the i
nner nodes represents the Non-Terminal symbols.
================================
10.What is the problem of left recursion and how can it be eliminated?11.Differ
entiate between top down and bottom up parsing. Give examples for each.12.Distin
guish between FIRST and FOLLOW.13.What is the significance of first & follow?14.
What do you mean by handle pruning?15. Describe the stack implementation of shif

t reduce parsing.16.Compare SLR, CLR and LALR parsers.17.What is the difference


between parse tree and syntax tree?18.Distinguish between S-attributed grammar a
nd L-attributed grammar.19.Compare synthesized attributes and inherited attribut
es.20.Describe how type checking of an expression is specified.21.What are the d
ifferent fields in an activation record?22.What do you mean by dangling referenc
e problem?23.What are the three representations of three address code statements
?24.What are the different optimization techniques used in compilers?25.What do
you mean by dead code elimination?26.What will be the output file created when
yacc translate.y
command is executed?27.Differentiate between a compiler and assembler.28.What is
the significance of a language processor?29.Differentiate between interpreter &
compiler.
VIVA QUESTIONS FOR COMPILER
1.What are the different phases of compilation?2.Differentiate between lexeme, t
oken and pattern.3.How input buffering is performed in compiler?4.Why is the inp
ut buffer organized into two halves?5.What is the use of sentinels in input buff
ering?6.What is a regular expression? Give examples.7.Give the structure of a le
x program.8.What is the output of a lex compiler.9.What are the different error
recovery strategies?
===============
. What is a translator?
02. Differentiate interpreters and compilers.
03. What are loaders and linkers?
04. What is an assembler?
05. What are the phases of a compiler?
06. What is bootstrapping a compiler?
07. What are the two parts of compilation? Explain briefly.
08. Explain in brief linear analysis.
09. Explain in brief hierarchical analysis.
10. Explain in brief semantic analysis.
11. Give the parse tree for the statement a := b + c * 60.
12. What is a symbol table?
13. Briefly explain code optimization.
14. What are rational preprocessors?
15. What is the use of scanner generator?
16. What are the characteristics of a high-level programming language?
17. What do you mean by syntax and semantics of a language?
18. Give the hierarchy of programming elements.
19. Explain in brief bookkeeping in compilation?
20. Give some four compiler-generator tools.
21. Explain Macros.
22. Explain in brief code generation phase.
23. Explain in brief intermediate code generation phase.
24. Mention the cousins of the compiler.
25. What are the functions of a linker?
26. What is an object program?
27. Define a token.
28. What is a preprocessor?
29. Give the format of a macro definition.
30. What is the need of syntax analysis?
31. What are the capabilities of CFG?
32. Define regular expressions.
33. Define a finite state automation.
34. What is a transition diagram? Give example.
35. What is a recognizer?
36. What is CFG? Give example.
37. What is a parse tree?
38. Consider the grammar:
S --> (L)/a
L --> L,S/S

What
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.

are the terminals, non-terminals and start symbols?


Differentiate NFA and DFA.
What are the types of derivation?
What is right-most derivation? Give example.
What is left-most derivation? Give example.
Explain canonical derivations.
What is left-sentential form?
What is right-sentential form?
What is sentence of a grammar G?
What is Context-Free Language?
What is regular definition? Give example.
What is a non-regular set?
What is a Lexical analyzer?
Write the algorithm for moving forward pointer in "input buffering" scheme.

52. What is the use of sentinels?


53. Distinguish tokens, patterns and lexemes.
54. What are the lexical-error recovery actions?
55. What is the need for input buffering?
56. Explain prefix and suffix of the string with example.
57. Explain proper prefix, proper suffix and proper substring with example.
58. What is subsequence of a sting?
59. Draw the transition diagram for identifiers.
60. What is the use of lexeme- beginning pointer and forward pointer?
61. What is a parser?
62. Write the role of parser.
63. Mention the error recovery strategies of parser.
64. What is ambiguity? Write the ways to eliminate ambiguity.
65. What is Left recursion? Write the rules to eliminate left recursion.
66. What is Left factoring? How do you eliminate it?
67. What is parsing table?
68. What is the use of LEX?
69. What is a handle?
70. What is handle pruning?
71. What is a transition diagram? Give example?
72. What is the need for separating the parser from scanner?
73. Translate the arithmetic expression a*-(b+c) into a syntax tree.
74. Define a Quadruple. How it is different from Triples.
75. What are Synthesized & Inherited Attributes?
76. What do you mean by back patching? Why we are going for back patching.
77. What are the three storage allocation strategies? Explain each in detail.
78. Need for code optimization.
79. What do you mean by Peep-hole optimization?
80. Construct DAG for the following exp (a+b)-(e-(c+d)).
81. Write the mnemonic code for (a+b)-(e-(c+d)).
82. What do you mean by symbol table.Explain.
83. What informations are stored in symbol table?
84. Explain about static & stack allocation.
85. What are the code optimization techniques?
86. Explain about common sub exp elimination & renaming of temp variables.
========================================================

You might also like