Translation Rules: It Contains Regular Expressions and Code Segments

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 22

1. Design of lexical Analyzer using lex/flex.

In computer science, lexical analysis, lexing or tokenization is the process of converting a


sequence of characters (such as in a computer program or web page) into a sequence of tokens
(strings with an assigned and thus identified meaning). A program that performs lexical analysis
may be termed a lexer, tokenizer, or scanner, though scanner is also a term for the first stage of
a lexer. A lexer is generally combined with a parser, which together analyze the syntax of
programming languages, web pages, and so forth.

Lex is a computer program that generates lexical analyzers.

Flex (fast lexical analyzer generator) is a free and open-source software alternative to lex. It is a
computer program that generates lexical analyzers (also known as "scanners" or "lexers").

The general format of Lex

{ declarations }
%%
{ transition rules }
%%
{ Auxiliary functions } (optional)

Declaration: This section includes declaration of variables, constants and regular definitions.
Translation rules: It contains regular expressions and code segments.
Form : Pattern {Action}
Pattern is a regular expression or regular definition.
Action refers to segments of code.
Auxiliary functions: LEX generates C code for the rules specified in the Rules section and places
this code into a single function called yylex(). In addition to this LEX generated code, the
programmer may wish to add his own code to the lex.yy.c file. The auxiliary functions section
allows the programmer to achieve this.
The following variables are offered by LEX to aid the programmer in designing sophisticated
lexical analyzers. These variables are accessible in the LEX program and are automatically
declared by LEX in lex.yy.c.
 yyin-
 yytext-
 yyleng-

The yyfunctions
 yylex()
 yywrap()
Example of lex program
/*** Definition section ***/
%{
/* C code to be copied verbatim */
#include <stdio.h>
%}
/* This tells flex to read only one input file */
%option noyywrap
%%

/*** Rules section ***/


/* [0-9]+ matches a string of one or more digits */
[0-9]+ {
/* yytext is a string containing the matched text. */
printf("Saw an integer: %s\n", yytext);
}
.|\n { /* Ignore all other characters. */ }
%%

/*** C Code section ***/


int main(void)
{
/* Call the lexer, then quit. */
yylex();
return 0;
}
2.Case study of working of virtual machine .

A virtual machine (VM) is an emulation of a computer system.


All virtual machines categorized in to 2 types
1. Hardware based or System based Virtual Machine
2. Software based or Application based or process based Virtual Machine
Hardware based virtual machines
Physically only one physical machine is there but several logical machines we can able to create
on the single physical machine with strong isolation (worked independently) of each other. This
type of virtual machines is called hardware based virtual machines.
Examples of hardware based virtual machines are
1. KVM (Kernel Based VM) for Linux systems 2. VMware 3. Cloud Computing
Software based virtual machines
These virtual machines acts as run time engine to run a particular programming language
applications. Examples of software based virtual machines are
1. JVM (Java Virtual Machine) acts as runtime engine to run Java applications
2. PVM (Parrot Virtual Machine) acts as runtime engine to run Perl applications
3. CLR (Common Language Runtime) acts as runtime engine to run .NET based applications.

Working of JVM

Class Loader Subsystem


It is mainly responsible for three activities.
 Loading: The Class loader reads the .class file, generate the corresponding binary data
and save it in method area.
 Linking: Performs verification, preparation, and (optionally) resolution.
 Initialization: In this phase, all static variables are assigned with their values defined in
the code and static block (if any). This is executed executed from top to bottom in a
class and from parent to child in class hierarchy.

Various memory area


Method area :In method area, all class level information like class name, immediate parent
class name, methods and variables information etc. are stored, including static variables. There
is only one method area per JVM, and it is a shared resource.
Heap area :Information of all objects is stored in heap area. There is also one Heap Area per
JVM. It is also a shared resource.
Stack area :For every thread, JVM create one run-time stack which is stored here. Every block
of this stack is called activation record/stack frame which store methods calls. All local variables
of that method are stored in their corresponding frame. After a thread terminate, it’s run-time
stack will be destroyed by JVM. It is not a shared resource.
PC Registers :Store address of current execution instruction of a thread. Obviously each thread
has separate PC Registers.
Native method stacks :For every thread, separate native stack is created. It stores native
method information.

Execution Engine
Execution engine execute the .class (bytecode). It reads the byte-code line by line, use data and
information present in various memory area and execute instructions. It can be classified in
three parts :-
 Interpreter : It interprets the bytecode line by line and then executes.
 Just-In-Time Compiler(JIT) : It is used to increase efficiency of interpreter. It compiles the
entire bytecode and changes it to native code so whenever interpreter see repeated
method calls ,JIT provide direct native code for that part so re-interpretation is not
required, thus efficiency is improved.
 Garbage Collector : It destroy un-referenced objects.

Java Native Interface (JNI) :

It is a interface which interacts with the Native Method Libraries and provides the native
libraries(C, C++) required for the execution. It enables JVM to call C/C++ libraries and to be
called by C/C++ libraries which may be specific to hardware.

Native Method Libraries:


It is a collection of the Native Libraries(C, C++) which are required by the Execution Engine.
3. Memory Implementation of 2D and 3D Array.

2D row-major
As mentioned above, in row-major layout, the first row of the matrix is placed in contiguous
memory, then the second, and so on:

2D column-major
Describing column-major 2D layout is just taking the description of row-major and replacing
every appearance of "row" by "column" and vice versa. The first column of the matrix is placed
in contiguous memory, then the second, and so on:
In 3D

Assuming 3 dimensions: rows, columns and depth. The following diagram shows the memory
layout of a 3D array with , in row-major:
4. Design a web page in PHP.

 Step 1
Create a folder on your server and name it "design".
 Step 2
Create the following files in the design folder:
'header.html', 'footer.html', 'right_column.html', 'left_column.html'
 Step 3
Create another folder and name it "pages"
 Step 4
In the "pages" directory, create a page and give it the name: 'main.html'
 Step 5
Now in the root directory create a file and give it the 'index.php'
 Step 6
Add the following code to your 'index.php' file (don't worry, it will be explained later!):
<?php
if (isset($_REQUEST['page']))
{
if($_REQUEST['page'] !="")
if(file_exists("pages/".$_REQUEST['page'].".html"))
$page_content = file_get_contents("pages/".$_REQUEST['page'].".html");
else
if (file_exists($_REQUEST['page'].".html"))
$page_content = file_get_contents($_REQUEST['page'].".html");
else
echo "<center>Page:".$_REQUEST['page']." does not exist! Please check the url and try
again!</center>";
}
else
$page_content = file_get_contents("pages/main.html");
$page_content = str_replace("!!HEADER!!",
file_get_contents("design/header.html"),$page_content);
$page_content = str_replace("!!LEFT_COLUMN!!",
file_get_contents("design/left_column.html"),$page_content);
$page_content = str_replace("!!RIGHT_COLUMN!!",
file_get_contents("design/right_column.html"),$page_content);
$page_content = str_replace("!!FOOTER!!",
file_get_contents("design/footer.html"),$page_content);
$page_content = str_replace("!!COMMON_TAGS!!",
file_get_contents("design/common_tags.html"),$page_content);

echo $page_content;

?>

 Step 7
Go to your 'main.html' and design it as you would like your website layout to look at the
end, only here, instead of adding the complete header design, add !!HEADER!! and then
go to the 'header.html' file that you created in the "design" folder. Now in the
'header.html', design the main header of your website. This design will be the header of
all your pages at the end.
Now do the same thing for the other designs, that is: put !!FOOTER!! and design
'footer.html', !!RIGHT_COLUMN!! and design 'right_column.html', put
!!LEFT_COLUMN!! and design 'left_column.html' respectively.

'main.html'

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Main Page - PHP Simple Templating System By Zeronese</title>
!!COMMON_TAGS!!
</head>
<body>
<table width="95%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td colspan="3"><center>
!!HEADER!!
</center>
</td>
</tr>
<tr>
<td class="column" width="25%" height="100%">!!LEFT_COLUMN!!</td>
<td> </td>
<td width="25%">!!RIGHT_COLUMN!!</td>
</tr>
<tr>
<td class="column" colspan="3"><center>
!!FOOTER!!
</center>
</td>
</tr>
</table>
</body>
</html>

'header.html'

<div class="header">Welcome To The PHP Simple Templating System</div>


'footer.html'

<div class="footer">
<center>
<a href="http://www.zeronese.net">PHP Simple Templating System is a Copy Right of
Zeronese.net</a>
</center>
</div>
'right_column.html'

<table class="column" width="100%" border="0" cellspacing="0" cellpadding="0">


<tr>
<td>Advertisement</td>
</tr>
<tr>
<td>Zeronese.net offers professional web design templates for both web designers and end
users. Save time and money and still get a high quality professional web site for business,
ecommerce or personal use. <a href="http://www.zeronese.net">Learn More...</a></td>
</tr>
</table>
'left_column.html'

<table class="column" width="100%" border="0" cellspacing="0" cellpadding="0">


<tr>
<td><a href="">Home</a></td>
</tr>
<tr>
<td><a href="!!WEBSITE_URL!!tutorial.html">Tutorial Page</a></td>
</tr>
<tr>
<td><a href="!!WEBSITE_URL!!sub-directory/page.html">Tutorial Sub Page</a></td>
</tr>
<tr>
<td><a href="http://www.zeronese.net">Visit Zeronese.net</a></td>
</tr>
</table>

and to add a little touch to our design, we create a 'styles.css' file in the design folder and add
the following code:

body{
background-color:#003399;
color:#FFFFFF;
}
a{
color:#FFFFFF;
font-weight:bold;
text-decoration:none;
}
a:hover{
text-decoration:underline;
}
.column{
background-color:#3366CC;
vertical-align:top;
}
.header{
background-color:#336699;
}
.footer{
background-color:#336699;
}

Try and test your design by using the browser to go


to: main_folder_of_files/index.php?page=main.html
5. Implementation of pointers in C++.

#include <iostream>

using namespace std;

int main() {

int *pc, c;

c = 5;

cout << "Address of c (&c): " << &c << endl;

cout << "Value of c (c): " << c << endl << endl;

pc = &c; // Pointer pc holds the memory address of variable c

cout << "Address that pointer pc holds (pc): "<< pc << endl;

cout << "Content of the address pointer pc holds (*pc): " << *pc << endl << endl;

c = 11; // The content inside memory address &c is changed from 5 to 11.

cout << "Address pointer pc holds (pc): " << pc << endl;

cout << "Content of the address pointer pc holds (*pc): " << *pc << endl << endl;

*pc = 2;

cout << "Address of c (&c): " << &c << endl;

cout << "Value of c (c): " << c << endl << endl;

return 0;

}
6.Write a program in Java to implement exception handling.

class Division {
public static void main(String[] args) {

int a, b, result;

Scanner input = new Scanner(System.in);


System.out.println("Input two integers");

a = input.nextInt();
b = input.nextInt();

// try block

try {
result = a / b;
System.out.println("Result = " + result);
}

// catch block

catch (ArithmeticException e) {
System.out.println("Exception caught: Division by zero.");
}
}
}
7. Write a program in C++ to implement different parameter passing Methods.

#include <iostream>
using namespace std;
// function declaration
void swap(int x, int y);
int main () {
// local variable declaration:
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;

// calling a function to swap the values.


swap(a, b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
return 0;
}

Output:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200

Passing by Pointer:
// C++ program to swap two numbers using
// pass by pointer.
#include <iostream>
using namespace std;
void swap(int* x, int* y)
{
int z = *x;
*x = *y;
*y = z;
}
int main()
{
int a = 45, b = 35;
cout << "Before Swap\n";
cout << "a = " << a << " b = " << b << "\n";
swap(&a, &b);
cout << "After Swap with pass by pointer\n";
cout << "a = " << a << " b = " << b << "\n";
}

Output:

Before Swap
a = 45 b = 35
After Swap with pass by pointer
a = 35 b = 45

Passing by Reference:

// C++ program to swap two numbers using


// pass by reference.
#include <iostream>
using namespace std;
void swap(int& x, int& y)
{
int z = x;
x = y;
y = z;
}
int main()
{
int a = 45, b = 35;
cout << "Before Swap\n";
cout << "a = " << a << " b = " << b << "\n";
swap(a, b);
cout << "After Swap with pass by reference\n";
cout << "a = " << a << " b = " << b << "\n";
}
Output:
Before Swap
a = 45 b = 35
After Swap with pass by reference
a = 35 b = 45
8. Write a program in Java to implement concurrent execution of a job using threads.

// Java code for thread creation by extending


// the Thread class
class MultithreadingDemo extends Thread
{
public void run()
{
try
{
// Displaying the thread that is running
System.out.println ("Thread " +
Thread.currentThread().getId() +
" is running");

}
catch (Exception e)
{
// Throwing an exception
System.out.println ("Exception is caught");
}
}
}

// Main Class
public class Multithread
{
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i=0; i<8; i++)
{
MultithreadingDemo object = new MultithreadingDemo();
object.start();
}
}
}
Output:
Thread 12 is running
Thread 15 is running
Thread 13 is running
Thread 17 is running
Thread 16 is running
Thread 14 is running
Thread 11 is running
Thread 10 is running
9. Implement different types of functions used in Prolog.

Defining four functions (it’s called predicates in prolog), addition, subtraction, multiplication,
and division. Each of them takes three parameters, the result is saved to the third parameter.

Prolog rules and facts


1 addition(A, B, C):- C is A + B.
2 subtraction(A, B, C):- C is A - B.
3 multiplication(A, B, C):- C is A * B.
4 division(A, B, C):- C is A / B.
Assume the above code is in a file called functions.pl, load the file in prolog and run the
following queries in prolog console. X is passed in as a variable holder, the result will be saved
to X when the function returns.

Queries
?- addition(2,3,X).
?- subtraction(4,2,X).
?- multiplication(3,4,X).
?- division(9, 3, X).
10. Implement Inheritance, Encapsulation & Polymorphism in C#.
Inheritance
public class ParentClass {
public ParentClass() {
Console.WriteLine("Parent Constructor.");
}
public void print() {
Console.WriteLine("I'm a Parent Class.");
}
}
public class ChildClass: ParentClass {
public ChildClass() {
Console.WriteLine("Child Constructor.");
}
public static void Main() {
ChildClass child = new ChildClass();
child.print();
}
}
Output
Parent Constructor.
Child Constructor.
I'm a Parent Class.

Encapsulation
using system;
public class Department {
private string departnamenane;
public int departed;
// Accessor.
public string GetDepartname() {
return departname;
}
// Mutator.
public void SetDepartname(string a) {
departname = a;
}
}
public static int Main(string[] args) {
Department d = new Department();
d.SetDepartname("CS&IT");
Console.WriteLine("The Department is :" + d.GetDepartname());
return 0;
}

Output:
The Department is: CS&IT

Polymorphism

public class Logger


{
public void Log(string message)
{
//Some code
}
public void Log(string message, Severity severity)
{
//Some code
}
}
public class Logger
{
public virtual void Log(string message)
{
Console.WriteLine("Inside the Log method of the base class Logger");
}
}
public class FileLogger : Logger
{
public override void Log(string message)
{
Console.WriteLine("Inside the Log method of the FileLogger class");
}
}
public static void Main(string[] args)
{
Logger logger = new FileLogger();
logger.Log("Hello World!")
}

You might also like