You are on page 1of 63

PUNE INSTITUTE OF COMPUTER TECHNOLOGY

DEPARTMENT OF COMPUTER ENGINEERING

LAB MANUAL
ACADEMIC YEAR: 2016-2017

DEPARTMENT: COMPUTER ENGINEERING

CLASS: B.E SEMESTER: I

SUBJECT: COMPUTER LABORATORY-I

INDEX OF LAB EXPERIMENTS

EXPT.
Problem statement Revised on
NO

Group A Assignments

1. Using Divide and Conquer Strategies design a function for Binary 15/06/2016
Search using C++/ Java/ Python/Scala.
2. Using Divide and Conquer Strategies design a class for 15/06/2016
Concurrent Quick Sort using C++.
3. Lexical analyzer for sample language using LEX. 15/06/2016

4. Parser for sample language using YACC. 15/06/2016

5. Intermediate code generation for sample language using LEX and 15/06/2016
YACC.
6. A6 :Based on Elective-I (Appendix I) 15/06/2016

Group B Assignments

1. 8-Queens Matrix is Stored using JSON/XML having first Queen 15/06/2016


placed, use back-tracking to place remaining Queens to generate
final 8-queens Matrix using Python.
2. Concurrent Implementation of traveling salesman problem. 15/06/2016

3. Implementation of 0-1 knapsack problem using branch and bound 15/06/2016


approach.
4. Code optimization using DAG. 15/06/2016

5. Code generation using DAG / labeled tree. 15/06/2016

6. Generating abstract syntax tree using LEX and YACC. 15/06/2016

7. Implementing recursive descent parser for sample language 15/06/2016

P:F-LTL-UG/03/R1 Page 1
8. Write a program to implement SLR Parsing algorithm using 15/06/2016
Python for the ordered input Set in XML { P E, EE+T,
ET, TT*F, TF, F(E), Fi }
9. B9: Based on Elective-I (Appendix I) 15/06/2016

10. B10: Based on Elective-I (Appendix I) 15/06/2016

11. B11: Based on Elective-I (Appendix I) 15/06/2016

12. B12: Based on Elective-I (Appendix I) 15/06/2016

13. B13: Based on Elective-I (Appendix I) 15/06/2016

Group C Assignments
1. Code generation using iburg tool. 15/06/2016

2. Cross compilation using XMLVM. 15/06/2016

3. Generate Huffman codes for a gray scale 8 bit image. 15/06/2016

4. Simulate JPEG like compression on a grayscale image and report 15/06/2016


the compression

Head of Department Subject Coordinator

(Computer Engineering) (Prof.Pujashree Vidap)

P:F-LTL-UG/03/R1 Page 2
Revised on: 15/06/2016

TITLE Divide and Conquer Strategy

PROBLEM Using Divide and Conquer strategies design a function


STATEMENT for binary search
/DEFINITION

OBJECTIVE To understand basic concepts of divide and conquer


strategy.

Operating Systems (64-Bit) 64-BIT Fedora 17 or latest 64-


BIT Update of Equivalent Open source OS or latest 64-BIT
S/W PACKAGES Version and update of Microsoft Windows 7 Operating
AND System onwards.
HARDWARE Programming Tools (64-Bit) Latest Open source update of
APPARATUS USED Eclipse Programming frame work, GTK+.

REFERENCES Horowitz and Sahani , Fundamentals of Computer


Algorithms, 2nd Edition. Published by University Press,
ISBN: 978 81 7371 6126.

Thomas H Cormen and Charles E.Leiserson,


Introduction to Algorithm, PHI, ISBN: 81-203-2141-3.

1. Problem definition

INSTRUCTIONS 2. Learning Objective


FOR 3. Learning Outcome
WRITING 4. Related Mathematics
JOURNAL
5. Class Diagram
6. Theory related to concepts
7. Source code
8. Conclusion

P:F-LTL-UG/03/R1 Page 3
Aim

Using Divide and Conquer strategy design a function to implement binary search .

Prerequisites

Basics of programming in Scala /Python/Java

Learning Objectives

Able to understand and use divide and conquer strategies.

Learning Outcome

After successfully completing this assignment, students should be able to


understand and implement binary search using Divide and Conquer strategy.

Related Mathematics

Mathematical Model
Consider S as a system

S= {s, e, x, y, f, DD, NDD | }

s = start state = {}

e= end state {0 | 1} where 0 represents not found. 1 represents found.

x = {L, n, key}

L = list of ordered numbers {xi | xi N xi < xi+1} where i = {1, 2, 3,.., n}

key = element to be searched. {x | x N}

P(L, n) = { <l , u> | <l, u> L & 1 l, u n } U {<l, n>}

|x| = U l + 1

INPUT: F(X) X

X=X U xi

SEARCH (): P(L, N) P(L, N)

f(x) = y s. t. x = <l, u> y =<, B> s. t. l B u and |y| = |x|/2 =l& =


B (u + l)/2-1

if key < x(u + l)/2 case 0: = (u + l)/2 + 1 B=u

if key > x(u + l)/2 case 1: no problem

P:F-LTL-UG/03/R1 Page 4
if key = x(u + l)/2 Empty

if key !=x(u + l)/2 & ( == B)

no problem set f(empty) = 0 and f(no problem) = 1

Output: O= {x | x (0, 1) where 0 represent found & 1 represent not found}

Success: Successful output represent success which is either number found or not
found.

Failure: If the given list is not sorted.

Concepts related Theory

Binary search can be effectively performed through divide and conquer strategy,
which reduces searching time. But for binary search it is mandatory that list must
be sorted.

The strategy involves three steps at each level of recursion.

Divide: - Divide the problem into a number of sub problems.

Conquer: - Conquer the sub problems by solving them recursively. If the sub
problem sizes are small enough, then just solve the sub problems in a straight
forward manner.

Combine: - Combine the solutions to the sub problems to form the solution
for the original problem.

Control Abstraction for divide and conquer strategy

Algorithm DAndC (P)

if small(P) then return S(P) //termination condition

Else

Divide P into smaller instances P1, P2, P3 Pk k1;

Apply DAndC to each of these sub problems.

Return Combine (DAndC(P1), DAndC (P2), DAndC (Pk)

P:F-LTL-UG/03/R1 Page 5
}

Computation time for divide and conquer strategy

T(n) = g(n) when n is small

= T(n1)+ T(n1)+ T(n2)+.+ T(nk)+ f(n) otherwise

T(n) denotes the time for DAndC on any input of size n.

g(n) is the time to compute the answer directly for small inputs.

f(n) is the time for dividing P and combining the solutions of sub problems.

T(n)= T(1) n=1

= aT(n/b)+f(n) n>1

Conclusion:

Thus, after successfully completing this assignment, students should be able to


understand and implement binary search with divide and conquer strategy.

P:F-LTL-UG/03/R1 Page 6
Revised on: 15/06/2016

TITLE Divide and Conquer Strategy for concurrent quick sort

PROBLEM Using Divide and Conquer Strategies design a class for Concurrent
STATEMENT Quick Sort using C++.
/DEFINITION

OBJECTIVE To understand basic concepts of divide and conquer strategy.


Understanding concurrent programming concept

S/W PACKAGES AND 1. Operating Systems (64-Bit) 64-BIT Fedora 17 or latest 64-BIT
Update of Equivalent Open source OS or latest 64-BIT Version and
HARDWARE update of Microsoft Windows 7 Operating System onwards.
APPARATUS USED
2. Programming Tools (64-Bit) Latest Open source update of Eclipse
Programming frame work, GTK+.

REFERENCES 1. Horowitz and Sahani, Fundamentals of Computer Algorithms,


2nd Edition. Published by University Press, ISBN: 978 81 7371
6126.

2. Thomas H Cormen and Charles E. Leiserson, Introduction to


Algorithm, PHI, ISBN:81-203-2141-3.

INSTRUCTIONS FOR 1. Problem definition

WRITING JOURNAL 2. Learning objective


3. Learning Outcome
4. Related Mathematics
5. Class Diagram
6. Concepts related Theory
7. Source code

8. Conclusion with outcome

P:F-LTL-UG/03/R1 Page 7
Aim

Using Divide and Conquer strategy design a class for Quick sort.

Prerequisites

Basic programming in C++.

Learning Objectives

Able to understand, divide and conquer strategies and concurrent programming.

Learning Outcome

After successfully completing this assignment, student should be able to


understand and implement Concurrent Quick sort using Divide and Conquer strategy.

Related Mathematics

Mathematical Model
Consider S as a system

S= {s, e, x, y, f, fc, Div, DD, NDD | }

s = start state = {}

e= end state {0 | 1} where 0 represents sorted. 1 represents not sorted.

X = {L, n}

L = list of unsorted numbers

{xi | xi N xi < xi+1 || xi > xi+1 || xi = xi+1} where i = {1, 2, 3,.., n}

p=pivot element p={xp | xp x }

INPUT: f(L) Y

PERMUTE={p | p is a permutation of x}

PRO(p)={x | x is a subsequence of p & p PERMUTE}

PSPACE= PRO(p) { } empty problem

p PERMUTE {} empty sequence

Div: PSPACE-->PSPACE X PSPACE

S.T Div() =(, )

Div (p)=(p1,p2)
P:F-LTL-UG/03/R1 Page 8
S.T |p|=|p1|+|p2|+1 & p1(l)=p(l) & p2(r)=p(r) & p1(r)<p2(l) & x p1 ,yp2 ,
x<=y

Assumption: pivot (p) provides pivot of problem P which is assumed to rightmost


element of p.

Div(p)= (,) if |p|=1

Output: Y=sorted list

Y = {X n/2, X p, X n/2} S.T {elements of(X n/2) < (X p) < elements of (X n/2) }

Success: Successful output represent list which is sorted.

Concepts related Theory

Quick sort can be effectively performed through divide and conquer strategy, which
reduces searching time.

The strategy involves three steps at each level of recursion.


1. Divide: - Divide the problem into a number of sub problems.
2. Conquer: - Conquer the sub problems by solving them recursively. If the sub
problem sizes are small enough, then just solve the sub problems in a straight forward
manner.
3. Combine: - Combine the solutions to the sub problems to form the solution for
the original problem.
Control Abstraction for divide and conquer strategy
Algorithm DAndC (P)
{
if small(P) then return S(P) //termination condition
else
{
Divide P into smaller instances P1, P2, P3 Pk k1;
Apply DAndC to each of these sub problems.
Return Combine (DAndC(P1), DAndC (P2), DAndC (Pk)
}
}

P:F-LTL-UG/03/R1 Page 9
Computation time for divide and conquer strategy
T(n) = g(n) when n is small
= T(n1)+ T(n1)+ T(n2)+.+ T(nk)+ f(n) otherwise
T(n) denotes the time for DAndC on any input of size n.
g(n) is the time to compute the answer directly for small inputs.
f(n) is the time for dividing P and combining the solutions of sub problems.
T(n)= T(1) n=1
= aT(n/b)+f(n) n>1

An introduction to threads:
With multithreading we are able to run multiple blocks of independent code
(functions) parallel with main() function.
Consider a thread a function running independent and simultaneous with the rest of
the code, and therefore not interfering with the execution order of 'main' program.
Initially, all C++ programs contain a single, default thread. All other threads must be
explicitly created by the programmer. 'normal' single threaded piece of code :
#include <iostream>
extern "C"
{
#include <unistd.h>
}
using namespace std;
void function1();
void function2();
int main()
{
function1();
function2();
return 0;
}
void function1()
{
cout << "hello..." << endl ;

P:F-LTL-UG/03/R1 Page 10
sleep(2); // fall asLeep here for 2 seconds...
}
void function2()
{
cout << " ....world" << endl ;

Compiling
If you want to compile the above code you need to include the pthread library. In
linux (using the GCC) use:
g++ program.cpp -pthread

Creating a thread

Using pthread_create() we can create multiple threads. We can use this call any
number of times and from anywhere in the code (also inside another thread). When a
thread is created it will be send to OS, which then schedules it for execution.

The pthread_create() call :

intpthread_create(pthread_t *thread, constpthread_attr_t *attr, void


*(*start_routine)(void*) , void *arg);

Parameters: -
thread : The unique identifier for the thread. This identifier has to be of type
pthread_t.
attr: This is an object which you can create for the thread with specific attributes for
the thread. It can be NULL if we want to use the default attributes.
start_routine: The function that the thread has to execute.
arg: The function argument. If we don't want to pass an argument, set it to NULL
returns :0 on success, some error code on failure.

Joining threads:

Joining threads is a method of synchronizing treads. Thewpthread_join() halts


execution of your code until the specified thread has been terminated. The
pthread_join() call :

intpthread_join(pthread_tth, void **thread_return);

P:F-LTL-UG/03/R1 Page 11
Parameters :

th: The unique identifier for the thread (as specified by pthread_tunique_identifier).

thread_return: A pointer to the value the thread returned. (as specified by


pthread_exit(return_value)).

Conclusion:

Thus, after successfully completing this assignment, you should be able to understand
and implement concurrent Quick sort with divide and conquer strategy.

P:F-LTL-UG/03/R1 Page 12
Revised on: 15/06/2016

TITLE
Lexical analyzer for HLL using LEX

PROBLEM
STATEMENT Lexical analyzer for sample language using LEX.
/DEFINITION
Understand the importance and usage of LEX automated tool
OBJECTIVE Appreciate the role of lexical analysis phase in compilation
Understand the theory behind design of lexical analyzers and
lexical analyzer generator
S/W PACKAGES Linux OS (Fedora 20), 64-bit Fedora or equivalent OS with 64-bit
AND Intel-i5/ i7 or latest higher processor computers, LEX, YACC
HARDWARE
APPARATUS
USED
1. A V Aho, R. Sethi, .J D Ullman, "Compilers:
Principles, Techniques, and Tools", Pearson Education, ISBN 81
REFERENCES
- 7758 - 590
2. J. R. Levine, T. Mason, D. Brown, "Lex & Yacc",
O'Reilly, 2000, ISBN 81-7366 -061-X. 8
3. K. Louden, "Compiler Construction: Principles and
Practice", Thomson Brookes/Cole (ISE), 2003, ISBN 981 - 243 -
694-4:page no.31-90
STEPS Refer theory, mathematical model,algorithm, test input, test
output
INSTRUCTIONS 1. Title
FOR 2. Problem Definition
WRITING 3. Theory and mathematical model
JOURNAL 4. State transition diagram
5. Algorithm
6. Source Code
7. Output
8. Conclusion

P:F-LTL-UG/03/R1 Page 13
Theory:

Lex is a tool for generating programs that perform pattern-matching on text. It is a


tool for generating scanners i.e. Programs which recognize lexical patterns in text.
The description of the scanner is in the form of pairs of regular expressions and C
code calls rules. Lex generates as output a C source file called lex.yy.c

The general format of lex source (lex specification) shall be:

Definitions

%%

Rules

%%

User Subroutines

The definition section is the place to define macros and to import header files
written in C. It is also possible to write any C code here, which will be copied
verbatim into the generated source file.
The rules section is the most important section; it associates patterns with C
statements. Patterns are simply regular expressions. When the lexer sees some
text in the input matching a given pattern, it executes the associated C code. This
is the basis of how lex operates.
The C code section contains C statements and functions that are copied
verbatim to the generated source file. These statements presumably contain code
called by the rules in the rules section. In large programs it is more convenient to
place this code in a separate file and link it in at compile time.
How the input is matched? :

When the generated scanner is run, it analyzes its input looking for strings which
match any of its patterns. If it finds more than one match, it takes the one matching
the most text (for trailing context rules, this includes the length of the trailing part,
even though it will then be returned to the input). If it finds two or more matches of
the same length, the rule listed first in the flex input file is chosen.
Once the match is determined, the text corresponding to the match (called the token)
is made available in the global character pointer yytext, and its length in the global
integer yyleng. The action corresponding to the matched pattern is then executed (a
more detailed description of actions follows), and then the remaining input is scanned
for another match.
If no match is found, then the default rule is executed: the next character in the input
is considered matched and copied to the standard output. Thus, the simplest legal flex

P:F-LTL-UG/03/R1 Page 14
input is: which generates a scanner that simply copies its input (one character at a
time) to its output.
Actions in lex :
The action to be taken when a RE is matched can be a C program fragment or the
special actions described below; the program fragment can contain one or more C
statements, and can also include special actions.

Four special actions shall be available:


| The action | means that the action for the next rule is the
action for this rule.
ECHO: Write the contents of the string yytext on the output.
REJECT: Usually only a single expression is matched by a given string in the input.
REJECT means "continue to the next expression that matches the current input", and
shall cause whatever rule was the second choice after the current rule to be executed
for the same input. Thus, multiple rules can be matched and executed for one input
string or overlapping input strings.
BEGIN The action: BEGIN newstate;
Regular Expressions in lex

"..." - Any string enclosed in double-quotes shall represent the


characters within the double-quotes as themselves, except that
backslash escapes.

<state>r, <state1,state2,...>r - The regular expression r shall be matched only


when the program is in one of the start conditions indicated by state, state1,
and so on.

r/x - The regular expression r shall be matched only if it is followed by an


occurrence of regular expression x

* - matches zero or more occurrences of the preceding expressions

[] - a character class which matches any character within the brackets. If the
first character is a circumflex '^' it changes the meaning to match any
character except the ones within brackets.

^ - matches the beginning of a line as the first characters of a regular


expression. Also used for negation within square brackets.

{} - Indicates how many times the previous pattern is allowed to match, when
containing one or two numbers.

P:F-LTL-UG/03/R1 Page 15
$ - matches the end of a line as the last character of a regular expressions

\ - used to escape metacharacters and a part of usual c escape sequences e.g '\n'
is a newline character while '\*' is a literal asterisk.

+ - matches one more occurrences of the preceding regular expression.

| - matches either the preeceeding regular expression or the following regular


expression.

( ) - groups a series of regular expressions together, into a new regular


expression.

Examples :

DIGIT [0-9]+

IDENTIFIER [a-zA-Z][a-zA-Z0-9]*

The functions or macros that are accessible to user code:

int yylex(void) : Performs lexical analysis on the input; this is the primary function
generated by the lex utility. The function shall return zero when the end of input is
reached; otherwise, it shall return non-zero values (tokens) determined by the actions
that are selected.

int yymore(void):When called, indicates that when the next input string is
recognized, it is to be appended to the current value of yytext rather than
replacing it; the value in yyleng shall be adjusted accordingly.

int yyless(int n) :Retains n initial characters in yytext, NUL-terminated, and treats


the remaining characters as if they had not been read;the value in yyleng shall be
adjusted accordingly.

int yywrap(void): Called by yylex() at end-of-file; the default yywrap() shall


always return 1. If the application requires yylex() to continue processing with
another source of input, then the application can include a function yywrap(),
which associates another file with the external variable FILE * yyin and shall
return a value of zero.

int main(int argc, char *argv[]): Calls yylex() to perform lexical analysis, then exits.
The user code can contain main() to perform application-specific operations, calling
yylex() as applicable.

Mathematical Model :

Let S be the solution for the system.

S= {St , E , I , O , F, DD , NDD}
P:F-LTL-UG/03/R1 Page 16
Where,

St is an initial state such that St={Fl | Fl is lex file}. At initial state, system consists of
one lex file with three sections.

E is a End state. E={Sc, Fc | Sc = success case which gives the lexemes-token table,
symbol table entries and Fc = failure case which gives the lexical errors}.

I= set of inputs I={Fi | Fi is an input file which consists of High Level Language
code}.

O= set of outputs

O={Op, Ot, Os, | Op is program after preprocessing i.e. after removing comments,
white spaces, Ot is lexeme-token table, Os is symbol table}.

F=A set of Functions.

F={f1,f2,f3 | f1,f2,f3:I O, function f1 removes comments and white spaces from


input program, function f2 generates the lexeme-token table from input program,
function f3 generates the symbol table from input program}

Function f1: I O

P:F-LTL-UG/03/R1 Page 17
Function f2: I O

Function f3: I O

DD=Deterministic Data

DD={x | x can be a token, data type, attribute}

NDD= Non-Deterministic Data

NDD={y | y can be a syntax or semantics of the input language}

P:F-LTL-UG/03/R1 Page 18
State Transition Diagram:

Algorithm:

1. Accept input filename (file is in HLL) as a command line argument.

2. Separate the tokens as identifiers, constants, keywords etc. and fill the
generic symbol table.

3. Check for lexical errors and give error messages if needed.

Test Input:

#include<stdio.h>

void main()

int a,b;

char bilateral;

a=3;

c=a+d;

Test Output:

Lexeme Token

#include<stdio.h> Directive

void Reserved

main() Reserved

{ Punctuation

int Keyword

a Identifier

P:F-LTL-UG/03/R1 Page 19
b Identifier

; Delimiter

char Reserved

bilateral Lexical error (as Identifier is more than 8 characters)

; Delimiter

a Identifier

= Operator

3 Constant

; Delimiter

c Identifier

= Operator

a Identifier

+ Operator

d Identifier

; Delimiter

} Punctuation

Symbol Table:

Symbol name Symbol Type Symbol Value

FAQs
1. What is the data structure used in Lexical phase of compiler
2. What are lexical errors
Practice Problem Statements:
1. Implement lexical analyser for JAVA along-with error handling

P:F-LTL-UG/03/R1 Page 20
2. Write a lex program to find character, word and line count from multiple files.
[Hint: Use yywrap() to handle EOF condition of first file and connect to
second file.]

3. Write a lex program to remove single and multiple line comments using state
concept.

4. Write a lex program that capitalizes all reserved words outside the comments
in a C program.

5. Write a program that takes R.E. and a filename as input and produces as
output all lines of file that contain a substring denoted by R.E.

6. Write a program to add error recovery routine or scheme for lex program to
enable it to continue to look for tokens in presence of errors.

P:F-LTL-UG/03/R1 Page 21
Revised on: 15/06/2016

TITLE Usage of YACC tool

TOPIC for
PROBLEM Parser for sample language using YACC.
STATEMENT
/DEFINITION

Be proficient on writing grammars to specify syntax


OBJECTIVE Understand the theories behind different parsing
strategies-their strengths and limitations
Understand how the generation of parser can be
automated
Be able to use YACC to generate parsers
S/W PACKAGES PC with the configuration as 64-bit Fedora or equivalent OS with
AND 64-bit Intel-i5/ i7 or latest higher processor computers,
HARDWARE LEX, YACC utility.
APPARATUS
USED
1. A V Aho, R. Sethi, .J D Ullman, "Compilers: Principles,
Techniques, and Tools", Pearson Education, ISBN 81 -
REFERENCES
7758 - 590
2. J. R. Levine, T. Mason, D. Brown, "Lex & Yacc",
O'Reilly, 2000, ISBN 81-7366 -061-X. 8
3. K. Louden, "Compiler Construction: Principles and
Practice", Thomson Brookes/Cole (ISE), 2003, ISBN 981
- 243 - 694-4:page no.226-254
STEPS Refer to theory, algorithm, test input, test output

INSTRUCTIONS 1. Title
FOR 2. Problem Definition
WRITING 3. Theory and mathematical model
JOURNAL
4. State transition diagram
5. Algorithm
6. Source Code
7. Output
8. Conclusion

P:F-LTL-UG/03/R1 Page 22
Theory:

Lex recognizes regular expressions, whereas YACC recognizes entire grammar. Lex
divides the input stream into tokens, while YACC uses these tokens and groups them
together logically.

The syntax of a YACC file :

%{

declaration section

%}

rules section

%%

user defined functions

%%

Declaration section:

Here, the definition section is same as that of Lex, where we can define all tokens and
include header files. The declarations section is used to define the symbols used to
define the target language and their relationship with each other. In particular, much
of the additional information required to resolve ambiguities in the context-free
grammar for the target language is provided here.

Grammar Rules in Yacc:

The rules section defines the context-free grammar to be accepted by the function
Yacc generates, and associates with those rules C-language actions and additional
precedence information. The grammar is described below, and a formal definition
follows.

The rules section is comprised of one or more grammar rules. A grammar rule has the
form:

A : BODY ;

The symbol A represents a non-terminal name, and BODY represents a sequence of


zero or more names, literals, and semantic actions that can then be followed by
optional precedence rules. Only the names and literals participate in the formation of
the grammar; the semantic actions and precedence rules are used in other ways. The
colon and the semicolon are Yacc punctuation.

P:F-LTL-UG/03/R1 Page 23
If there are several successive grammar rules with the same left-hand side, the vertical
bar | can be used to avoid rewriting the left-hand side; in this case the semicolon
appears only after the last rule. The BODY part can be empty.

Programs Section

The programs section can include the definition of the lexical analyzer yylex(), and
any other functions; for example, those used in the actions specified in the grammar
rules. It is unspecified whether the programs section precedes or follows the
semantic actions in the output file; therefore, if the application contains any macro
definitions and declarations intended to apply to the code in the semantic actions, it
shall place them within "%{ ... %}" in the declarations section.

Interface to the Lexical Analyzer

The yylex() function is an integer-valued function that returns a token number

representing the kind of token read. If there is a value associated with the

token returned by yylex() (see the discussion of tag above), it shall be

assigned to the external variable yylval.

Running Lex and Yacc :

Generate y.tab.c and y.tab.h files using 'yacc -d <filename.y>

Generate a .c file using 'lex <filename.l>

Link the two files together using gcc y.tab.c lex.yy.c lfl

Mathematical Model :

Let S be the solution for the system.

S= { St , E , I , O , F, DD , NDD}

Where, St is an initial state such that St={Fl,Fy | Fl is lex file and Fy is a yacc file}.
At initial state, system consists of two files, each with three sections.

E is a End state.

E={Sc, Fc | Sc = success case which shows that input is syntactically correct and

Fc = failure case which mentions that syntax is syntactically incorrect}.

I= set of inputs

I={Fi | Fi is an input file which consists of High Level Language code}.

P:F-LTL-UG/03/R1 Page 24
O={Op, Ot, Os, Oc | Op is program after preprocessing i.e. after removing
comments, white spaces, Ot is lexeme-token table, Os is symbol table, Oc is console
output which mention that syntax of statements of input program is correct or not}.

F=A set of Functions.

F={f1,f2,f3,f4 | f1,f2,f3:I O, function f1 removes comments and white spaces from


input program, function f2 generates the lexeme-token table from input program,
function f3 generates the symbol table from input program, function f4 checks
whether the statements of input program is as per the context free grammar mentioned
in Fy or not}

Function f1: I O

Function f2: I O

P:F-LTL-UG/03/R1 Page 25
Function f3: I O

Function f4: I O

DD=Deterministic Data

DD={x | x is HLL's syntax which includes brackets, keywords, variables, functions


definitions etc.}

NDD= Non-Deterministic Data

NDD={y | y is Semantic of the statements of Language}

P:F-LTL-UG/03/R1 Page 26
State Transition Diagram:

Algorithm :

1. Write Lex code to separate out the tokens.

2. Write YACC code to check the syntax of the sentence.

3. Accept a input/sentence from the user

4. If input is as per syntax print 'accepted' else 'rejected'

Test Input for Natural Language Parser:

I am a boy

Test Output:

Statement is syntactically correct/Syntax correct

Test Input:

I boy am

Test Output:

Statement is syntactically wrong/Syntax error

FAQs
1. Which is the file generated as output as a result of YACC translation
2. How LEX communicates with YACC
3. Is there any other parser generator/ syntax analysis generator other than
YACC?
4. What is state machine?
5. Which phase is the driver of compiler?
6. How to debug YACC specification file

P:F-LTL-UG/03/R1 Page 27
Practice Problem Statements:
1. Write a lex and yacc program for parsing .asm file ( assembly language).

2. Write a lex and yacc program for parsing SQL statements which are in file
[insert , update, select and delete statements]

3. Write a lex and yacc program for parsing class definition in java [which may
include implementation of interface and inheritance].

4. Write a lex and yacc program for parsing html file along with counting
opening and closing tags

5. Implement a natural language parser using LEX & YACC

P:F-LTL-UG/03/R1 Page 28
Revised on: 15/06/2016

TITLE Intermediate code generation for sample language using LEX


and YACC.
PROBLEM 1. Write a LEX and YACC program to generate Intermediate
STATEMENT Code for arithmetic expression
/DEFINITION 2. Write a LEX and YACC program to generate Intermediate
Code for subset of C (If,else,while)
1. To understand the fourth phase of a compiler:
Intermediate code generation (ICG)
OBJECTIVE
2. To learn and use compiler writing tools.
3. Understand and learn how to write three address code
for given statement.
S/W PACKAGES Linux OS (Fedora 20), PC with the configuration as 64-bit Fedora
AND or equivalent OS with 64-bit Intel-i5/ i7 or latest higher processor
HARDWARE computers,
APPARATUS FOSS tools, LEX, YACC,
USED
1. A V Aho, R. Sethi, .J D Ullman, "Compilers:
Principles, Techniques, and Tools", Pearson Education, ISBN
REFERENCES
81 - 7758 - 590
2. J. R. Levine, T. Mason, D. Brown, "Lex & Yacc",
O'Reilly, 2000, ISBN 81-7366 -061-X. 8
3. K. Louden, "Compiler Construction: Principles and
Practice", Thomson Brookes/Cole (ISE), 2003, ISBN 981 -
243 - 694-4:page no.31-90
STEPS Refer theory, algorithm, test input, test output

INSTRUCTIONS 1. Title
FOR 2. Problem Definition
WRITING 3. Theory and mathematical model
JOURNAL
4. State transition diagram
5. Algorithm
6. Source Code
7. Output
8. Conclusion

P:F-LTL-UG/03/R1 Page 29
THEORY:

Introduction

In the analysis-synthesis model of a compiler, the front end analyzes a source program
and creates an intermediate representation, from which the back end generates target
code. Ideally, details of the source language are confined to the front end, and details
of the target machine to the back end. The front end translates a source program into
an intermediate representation from which the back end generates target code. With a
suitably defined intermediate representation, a compiler for language i and machine j
can then be built by combining the front end for language i with the back end for
machine j. This approach to creating suite of compilers can save a considerable
amount of effort: m x n compilers can be built by writing just m front ends and n back
ends.

Benefits of using a machine-independent intermediate form are:

1. Compiler for a different machine can be created by attaching a back end for the
new machine to an existing front end.

2. A machine-independent code optimizer can be applied to the intermediate


representation.

Three ways of intermediate representation:

Syntax tree

Postfix notation

Three address code

The semantic rules for generating three-address code from common programming
language constructs are similar to those for constructing syntax trees or for generating
post-fix notation.

Three-address code:

Each statement generally consists of 3 addresses, 2 for operands and 1 for result.

X:=Y op Z where X,Y,Z are variables, constants or compiler generated variables.

Advantages of three-address code:

Complicated arithmetic expressions and of nested flow-of-control statements makes


three-address code desirable for target code generation and optimization.

P:F-LTL-UG/03/R1 Page 30
The use of names for the intermediate values computed by a program allows three
address codes to be easily rearranged unlike post-fix notation.

Three-address code is a liberalized representation of a syntax tree or a dag in which


explicit names correspond to the interior nodes of the graph. The syntax tree and dag
are represented by the three-address code sequences. Variable names can appear
directly in three address statements.

Types of Three-Address Statements:

The common three-address statements are:

1. Assignment statements of the form x : = y op z, where op is a binary


arithmetic or logical operation.

2. Assignment instructions of the form x : = op y, where op is a unary operation.


Essential unary operations include unary minus, logical negation, shift
operators, and conversion operators that, for example, convert a fixed-point
number to a floating-point number.

3. Copy statements of the form x : = y where the value of y is assigned to x.

4. The unconditional jump goto L. The three-address statement with label L is


the next to be executed.

5. Conditional jumps such as if x rel op y goto L. This instruction applies a


relational operator (<, =, >=, etc. ) to x and y, and executes the statement with
label L next if x stands in relation rel op to y. If not, the three-address
statement following if x relop y goto L is executed next, as in the usual
sequence.

6. param x and call p, n for procedure calls and return y, where y representing a
returned value is optional. For example,

param x1

param x2

param xn call p,n

generated as part of a call of the procedure p(x1, x2, . ,xn ).

7. Indexed assignments of the form x : = y[i] and x[i] : = y.

8. Address and pointer assignments of the form x : = &y , x : = *y, and *x : = y.

P:F-LTL-UG/03/R1 Page 31
9. Implementation of Three-Address Statements: A three-address statement is an
abstract form of intermediate code. In a compiler, these statements can be
implemented as records with fields for the operator and the operands. Three
such representations are: Quadruples, Triples, Indirect triples.

A. Quadruples:

A quadruple is a record structure with four fields, which are, op, arg1, arg2
and result.

The op field contains an internal code for the operator. The 3 address
statement x = y op z is represented by placing y in arg1, z in arg2 and x in
result.

The contents of fields arg1, arg2 and result are normally pointers to the
symbol-table entries for the names represented by these fields. If so,
temporary names must be entered into the symbol table as they are created.

Fig a) shows quadruples for the assignment a : b * - c + b *- c

B. Triples:

To avoid entering temporary names into the symbol table, we might refer to a
temporary value by the position of the statement that computes it.

If we do so, three-address statements can be represented by records with only


three fields: op, arg1 and arg2.

The fields arg1 and arg2, for the arguments of op, are either pointers to the
symbol table or pointers into the triple structure ( for temporary values ).

Since three fields are used, this intermediate code format is known as triples.

op arg1 arg2 Result

(0) uminus c t1

(1) * b t1 t2

(2) uminus c t3

(3) * b t3 t4

(4) + t2 t4 t5

P:F-LTL-UG/03/R1 Page 32
(5) := t5 a

Fig(a)

Mathematical Model :

Let S be the solution for the system.

S= {St , E , I , O , F, DD , NDD}

Where, St is an initial state such that St={Fl,Fy | Fl is lex file and Fy is a yacc file}.
At initial state, system consists of two files, each with three sections.

E is a End state.

E={Sc, Fc | Sc = success case which generate intermediate three-address code. and Fc


= failure case which mentions that unable to generate three-address code}.

I= set of inputs

I={Fi | Fi is an input file which consists of High Level Language code}.

O={Os, Oc | Os is symbol table, Oc is console output which mention that three-


address code of input program.}.

F=A set of Functions.

F={f1 | f1:I O, function f1 generates the three-address code from input program}

Function f1: I O

DD=Deterministic Data

P:F-LTL-UG/03/R1 Page 33
DD={x | x is HLL's syntax which includes brackets, keywords, variables, functions
definitions etc.}

NDD= Non-Deterministic Data

NDD={y | y is Semantic of the statements of Language}

ALGORITHM:

Write a LEX and YACC program to generate Intermediate Code for arithmetic
expression

LEX program

1. Declaration of header files specially y.tab.h which contains declaration for Letter,
Digit, expr.

2. End declaration section by %%

3. Match regular expression.

4. If match found then convert it into char and store it in yylval.p where p is pointer
declared in YACC

5. Return token

6. If input contains new line character (\n) then return 0

7. If input contains . then return yytext[0]

8. End rule-action section by %%

10. Declare main function

a. open file given at command line

b.if any error occurs then print error and exit

c. assign file pointer fp to yyin

d.call function yylex until file ends

11. End.

YACC program:

1. Declaration of header files

2. Declare structure for three address code representation having fields of argument1,
argument2, operator, result.
P:F-LTL-UG/03/R1 Page 34
3. Declare pointer of char type in union.

4. Declare token expr of type pointer p.

5. Give precedence to *,/.

6. Give precedence to +,-.

7. End of declaration section by %%.

8. If final expression evaluates then add it to the table of three address code.

9. If input type is expression of the form.

a. exp+exp then add to table the argument1, argument2, operator.

b. exp-exp then add to table the argument1, argument2, operator.

c. exp*exp then add to table the argument1, argument2, operator.

d. exp/exp then add to table the argument1, argument2, operator.

e. (exp) then assign $2 to $$.

f. Digit OR Letter then assigns $1 to $$.

10. End the section by %%.

11. Declare file *yyin externally.

12. Declare main function and call yyparse function untill yyin ends

13. Declare yyerror for if any error occurs.

14. Declare char pointer s to print error.

15. Print error message.

16. End of the program.

Test Input:

main(){

int x,y,z,i;

x=5;

i=6;

y=8;

z=1;
P:F-LTL-UG/03/R1 Page 35
if(x<=7){

i=i+1+y*z;

if(x==1){

y=3;

if(x<=2){

y=2;

else{

x=5;

else{

i=i-1-y*z;

while(x>0){

x=x-1;

if(x>=7){

i=i+1+y*z;

else{

i=i-1-y*z;

while(x>0){

x=x-1;

}
P:F-LTL-UG/03/R1 Page 36
}

Steps to execute the program:

$ lex filename.l (eg: comp.l)

$ yacc -d filename.y (eg: comp.y)

$gcc lex.yy.c y.tab.c

$./a .out

Output:

The three-address code:

0 = 5 x

1 = 6 i

2 = 8 y

3 = 1 z

4 <= x 7 t0

5 IF t0 0 20

6 + i 1 t1

7 * y z t2

8 + t1 t2 t3

9 = t3 i

10 == x 1 t4

11 IF t4 0 17

12 = 3 y

13 <= x 2 t5

14 IF t5 0 16

15 = 2 y

16 GOTO 19

17 ELSE
P:F-LTL-UG/03/R1 Page 37
18 = 5 x

19 GOTO 25

20 ELSE

21 - i 1 t6

22 * y z t7

23 - t6 t7 t8

24 = t8 i

25 > x 0 t9

26 WHILE t9 0 30

27 - x 1 t10

28 = t10 x

29 GOTO 26

30 >= x 7 t11

Similarly .

Symbol Table:

i int

z int

y int

x int

FAQs

1. What are the different forms of ICG?

2. What are the difference between syntax tree and DAG?

3. What are advantages of 3-address code?

4. Which representation of 3-address code is better than other and why? Justify.

5. What is role of Intermediate code in compiler?

P:F-LTL-UG/03/R1 Page 38
Practice Problem Statements:

1. Write a program to generate intermediate three-address code statements for 'for


statement' construct in C language.

2. Write a program to generate intermediate three-address code statements for 'switch


statement' construct in C language.

3. Write a program to implement the syntax directed definition for translating


booleans to three addresses code.

P:F-LTL-UG/03/R1 Page 39
IP Revised on: 15/06/2016

TITLE Display Histogram of a image

PROBLEM Design a class using C++ to read a gray scale TIFF image
STATEMENT file of a dental digital X-Ray or Medical X-Ray or an
/DEFINITION Areal view Image, design Class to calculate histogram to
return a CList. Design Image Display class to display
histogram of a image.
To learn image file formats such as TIFF
OBJECTIVE To implement program using C++ for reading,
displaying image and histogram
1.Operating Systems (64-Bit)64-BIT Fedora 17 or latest
64-BIT Update of Equivalent Open source OS or latest
S/W PACKAGES AND
64-BIT Version and update of Microsoft Windows 7
HARDWARE Operating System onwards
APPARATUS USED
2. Programming Tools (64-Bit), Latest Open source
update of Eclipse Programming frame work, GTK+
REFERENCES Malay K. Pakhira, Digital Image processing and Pattern
Recognition,PHI, 2014,ISBN-978-81-203-4091-6.
Jayaraman, "Digital Image Processing" Mc Graw Hill
1. Problem definition
INSTRUCTIONS FOR 2. Learning objective

WRITING JOURNAL 3. Learning Outcome


4. Related Mathematics
5. Class Diagram
6. Concepts related Theory
7. Program code with proper documentation.
8. Output of program. Conclusion and applications.
(the verification and testing of outcomes).

P:F-LTL-UG/03/R1 Page 40
Aim

Design a class using C++ to read a gray scale TIFF image file of a dental digital X-
Ray or Medical X-Ray or an Areal view Image, design Class to calculate histogram
to return a CList, Design Image Display class to display histogram of a image.

Prerequisites

Concept of various image file formats attributes such as TIFF


Object oriented programming features.

Learning Objectives

To understand the basic graphic functions in C/C++.

To understand the basic system defined line drawing functions.

Learning Outcome

After successfully completing this assignment, you should be able to understand and
implement different line drawing functions in Java

Related Mathematics

Mathematical Model

Let us consider S as a system for displaying a gray scale image with TIFF format, and
display its histogram.

M={ S, E, F, X, Y, DD, NDD, Success, Failure}

S=start state

E=end state

F= {F1, F2, F3}

Identify the inputs

S =Start state

E=End state

Fn= { fread ,fdisplay ,fhisto, fcount}

X= {x |x [0 ---255] N}

Y = {count}

DD = Deterministic data; count <= height x width

P:F-LTL-UG/03/R1 Page 41
NDD = Non deterministic data; here the image format other than TIFF format is
invalid

1. Operations performed :
{ fread ,fdisplay ,fhisto ,fcount }

1. fread = reads the TIFF grayscale image


2. fdisplay = display the TIFF image specifying its dimensions(height,
width) and pixel values
3. fcount =it keeps the count of every pixel value
4. fhisto = it displays the histogram using the count value, histogram is the
graph of x-axis on pixels versus y-axis of count of the pixels
Output:

O= graph of pixel intensity verses count

Data Structures used:

For A, B, C, D, E: Array

Sr. Mathematical Model Description Observation


No.

1 I = {(x1,y1),(x2,y2), (x3,y3), I be the end-points of As the Line


,, (xn ,yn )} given line segment as input. segment
coordinates will be
stored in separate
array forms i.e.(Xi,
Yi)

2 O= {O1, O2, O3,, On } O will store output of As the size of


system Output is variable
Array can be used

3 F1( set_pixel(x, y)) = A' A= {d |d contains the Reusable


information about input component
values of pixel}

P:F-LTL-UG/03/R1 Page 42
4 F2(change_pixel(X, Y))= B' = {d| 'd' consists the
B' absolute value of change in
pixel parameters}

I= {L} | t > 0

Let fe be a rule of L into B'


such that for given line
segment; it returns x and y
intervals.

fe(L) | B'.

(dx1,dy1)
(dx2,dy2)
(dx3,dy3)
.
.
.

5 F3(slope_line(X, Y)) = C' I= {L} | t > 0 Reusable


component
Let fe be a rule of L into C'
such that for given line
endpoints; it returns slope of
line.

fe(L) | C'.
(x1,y1) m1
(x2,y2) m2
(x3,y3) m3
. .
. .
. .
.

6 .
F4(change_interval(X, Y)) D' = {dX, dY} | t > 0 Reusable
= D' component
fe(X, .Y) | D'.

P:F-LTL-UG/03/R1 Page 43
7 F5(get_Newpixel (X, Y)) E' = {X', Y'} | t > 0
= E'
fe(X, Y) | E'.

(x1,y1)
(x2,y2) (x1',y1')
(x3,y3) (x2',y2')
. (x3',y3')
. .
. .
.
.
.

.
Success: Finally, we can display the TIFF image and draw a histogram for the TIFF
grayscale image.

Failure:
Image formats other than TIFF are used, histogram and image can not be displayed.
4. Concepts related Theory

Histogram:

A histogram is a graph. A graph that shows frequency of anything. Usually histogram


have bars that represent frequency of occurring of data in the whole data set.

Histogram of an image , like other histograms also shows frequency. But an image
histogram , shows frequency of pixels intensity values. In an image histogram, the x
axis shows the gray level intensities and the y axis shows the frequency of these
intensities.

The x axis of the histogram shows the range of pixel values. Since its an 8 bpp image ,
that means it has 256 levels of gray or shades of gray in it. Thats why the range of x
axis starts from 0 and end at 255 with a gap of 50. Whereas on the y axis , is the count
of these intensities.

P:F-LTL-UG/03/R1 Page 44
Applications of Histograms:

Histograms have many uses in image processing. The first use as it has also been
discussed above is the analysis of the image. We can predict about an image by just
looking at its histogram. Its like looking an x ray of a bone of a body.

The second use of histogram is for brightness purposes. The histograms have wide
application in image brightness. Not only in brightness, but histograms are also used
in adjusting contrast of an image.

Another important use of histogram is to equalize an image.

And last but not the least; histogram has wide use in thresholding. This is mostly used
in computer vision.

TIFF Library:

LIBTIFF is a C graphic library provides support for the Tag Image File Format
(TIFF), a widely used format for storing image data. This library provides means to
easily access and create TIFF image files. LIBTIFF will be the supported image
manipulating package supported in the class.

P:F-LTL-UG/03/R1 Page 45
1. Setting Up The VC++ 6.0 Project To Use LIBTIFF

To use LIBTIFF in your existing VC++ 6.0 Project/WorkSpace, you need to do the
following setting modifications:

1. Open your existing Project/WorkSpace file in VC++ 6.0


2. Choose Project-Settings... menu item.
3. Click "C/C++" tab in the dialog.
4. Choose "Preprocessor" item in the "Category:" menu.
5. Choose "All Configurations" item in the "Settings for:" menu.
6. ADD (not replacing) the following path to the "Additional Include
Directories:" field: P:\course\cs638-gleicher\public\include\libtiff\, this will
allow the compiler to find the header files for the library

The following steps will make the compiler use correct method to generate the
machine code:

1. Choose "Code Generation" item from the "Category" menu


2. Choose "Win32 Release" item in the "Settings for:" menu
3. Select "Multithreaded" option in the "Use run-time library:" menu.
4. Select "Win32 Debug" item in the "Settings for:" menu
5. Set "Use run-time library" menu to the option "Debug
Multithreaded".
6. Click "Link" tab in the dialog.
7. Select "Input" item in the "Category:" menu.
8. Choose "All Configurations" item in the "Settings for:" menu
9. Add (not replacing) the following path to the "Additional
library path:" field: P:\course\cs638-gleicher\public\lib\, this will allow the
linker to find the library binary files of LIBTIFF.

By carrying out the following steps, we tell the linker to link in the correct libtiff
library file.

1. Choose "Win32 Release" item in the "Settings for:" menu


2. Add (without change original) following text to the
"Object/library modules:" field: libtiff.lib
3. Choose "Win32 Debug" item in the "Settings for:" menu
4. Add (without change original) following text to the
"Object/library modules:" field: dlibtiff.lib.
5. Click "Ok".

P:F-LTL-UG/03/R1 Page 46
2. Using LIBTIFF in your code.

1. Add the following line in the beginning of your code file(s) to


include the libtiff header file:

2. #include <tiffio.h>

3. Open file and read

1. You must open the file with the following line to read the tiff file:
TIFF *tif=TIFFOpen("input.tif", "r");
2. Then you must get the size of the image from the opened file:
#define uint32 unsigned long
TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);
// uint32 width;
TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height);
// uint32 height;
3. You should use the LIBTIFF library memory allocation functions to
get space to store the image:
uint32 npixels=width*h;
raster=(uint32 *) _TIFFmalloc(npixels *sizeof(uint32));
[Note: Though it works under Win32, you should not use the
C-"malloc/free" and the C++-"new/delete" functions/operators
to do the memory management for the reading buffer]

4. Now you are able to read the image from the TIFF file using the
following function:
TIFFReadRGBAImage(tif, width, height, raster, 0);

Note: You should always check the return value of the function to
make sure that there is no error occurred in the reading process.
Returning 1 means read was successful, and if 0 is returned, some type
of error occured.

What you have now is an array (raster) of pixel values, one for each
pixel in the image, and each pixel is a 4-byte value. Each of the bytes
represent a channel of the pixel value (RGBA). Each channel is
represented by an integer value from 0 to 255.

To get each of the individual channel of a pixel use the function:

P:F-LTL-UG/03/R1 Page 47
char X=(char )TIFFGetX(raster[i]); // where X can be the channels R,
G, B, and A.
// i is the index of the pixel in the raster.

Important: Remember that the origin of the raster is at the lower left
corner. You should be able to figure out the how the image is stored in
the raster given that the pixel information is stored a row at a time!

5. After you are finished with the raster you should destroy it and free up
the memory:_TIFFfree(raster);
6. Always Close the File when you are done with it. TIFFClose(tif);

7. Creating a new TIFF image file;

7.1 You must open the file with the following line to write the tiff file,
this will create the file if it does not exist, and replace the file if it
does.
7.2 TIFF *out= TIFFOpen("new.tif", "w");
7.3 Your image data should be store in some type of array of char's.
int sampleperpixel = 4; // or 3 if there is no alpha channel,
you should get a understanding of alpha in class soon.

char *image=new char [width*height*sampleperpixel];

Then format of the pixel information is store in the order


RGBA, into the array, each channel occupies 1 byte (char).

7.4 Now we need to set the tags in the new image file, and the essential
ones are the following:
TIFFSetField (out, TIFFTAG_IMAGEWIDTH, width); // set
the width of the image
TIFFSetField(out, TIFFTAG_IMAGELENGTH, height);
// set the height of the image
TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL,
sampleperpixel); // set number of channels per pixel
TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, 8); //
set the size of the channels
TIFFSetField(out, TIFFTAG_ORIENTATION,
ORIENTATION_TOPLEFT); // set the origin of the
image.
// Some other essential fields to set that you do not have to
understand for now.
TIFFSetField(out, TIFFTAG_PLANARCONFIG,
PLANARCONFIG_CONTIG);
P:F-LTL-UG/03/R1 Page 48
TIFFSetField(out, TIFFTAG_PHOTOMETRIC,
PHOTOMETRIC_RGB);
7.5 We will use most basic image data storing method provided by the
library to write the data into the file, this method uses strips, and
we are storing a line (row) of pixel at a time. This following code
writes the data from the char array image into the file:
tsize_t linebytes = sampleperpixel * width; // length in
memory of one row of pixel in the image.

unsigned char *buf = NULL; // buffer used to store the


row of pixel information for writing to file
// Allocating memory to store the pixels of current row
if (TIFFScanlineSize(out)linebytes)
buf =(unsigned char *)_TIFFmalloc(linebytes);
else
buf = (unsigned char
*)_TIFFmalloc(TIFFScanlineSize(out));

// We set the strip size of the file to be size of one row of


pixels
TIFFSetField(out, TIFFTAG_ROWSPERSTRIP,
TIFFDefaultStripSize(out, width*sampleperpixel));

//Now writing image to the file one strip at a time


for (uint32 row = 0; row < h; row++)
{
memcpy(buf, &image[(h-row-1)*linebytes], linebytes);
// check the index here, and figure out why not using
h*linebytes
if (TIFFWriteScanline(out, buf, row, 0) < 0)
break;
}

7.6 Finally we close the output file, and destroy the buffer
(void) TIFFClose(out);

if (buf)
_TIFFfree(buf);

7.7 One suggestion for working with the image data is to convert the
raster structure into the char image[] structure for image analysis
and manipulations.
7.8 With the above example you should be able to have the basic way
of read and write TIFF image files.
P:F-LTL-UG/03/R1 Page 49
Trouble Shooting.

1. Error that indicate LIBTIFF library include/header file (.h files) not found
during compilation
2. You did not set the "Directories" "Include Files" path correctly for the
LIBTIFF library, refer to steps 1.3-1.6
3. Error that indicate unresolved function definitions, or error during linking
process
4. You did not correctly add the dlibtiff.lib wsock32.lib to the "Link" option in
the Project-Setting, refer to steps 1.15-1.19
You did not correctly set the path for the library files for LIBTIFF, refer to
steps 1.12-1.15.
5. Other compile errors
1. Most likely caused by some problem in your code.
2. Error/Crash during the execution of your program
3. Most likely caused by some problem in your code.
4. The linker complains:
5. LINK : warning LNK4098: defaultlib "LIBCMTD" conflicts with
use of other libs; use /NODEFAULTLIB:library
This means that you did not compile your program with the correct
code generation settings, described above, refer to steps 1.7-1.11

Class Diagram :

Histogram

+(count, intensities)

+DrawGraph(count)

7. Add the following line in

Conclusion:

Thus, after successfully completing this assignment, you should be able to understand
& Implement different line drawing functions in C/ C++.

P:F-LTL-UG/03/R1 Page 50
CNDM Revised on: 15/06/2016
TITLE Network design and implementation in NS3
PROBLEM A company has three offices at remote locations with
STATEMENT requirement of interoperability with remote services.
/DEFINITION Each office has a server, TCP/IP and different users
including administrator, privileged users and common
clients. Design a network model for the same.
Demonstrate the network model using NS3
OBJECTIVE To understand the installation and working of NS3.
1. Operating Systems
S/W PACKAGES AND (64-Bit)64-BIT Fedora 17 or latest 64-BIT Update of
Equivalent Open source OS or latest 64-BIT Version
HARDWARE
APPARATUS USED 2. Programming Tools (64-Bit)
Latest Open source update of Eclipse Programming
frame work, GTK+
3. Programming languages like C++, Python, etc.
4. ns-allinone-3.15 or latest version and netanim
5. editors like gedit, vi editor, etc.
REFERENCES George F. Riley, Thomas R. Henderson,
Modeling and Tools for Network
Simulation, Springer Berlin Heidelberg,
2010, ISBN 978-3-642-12330-6
William Stallings, Wireless Communications &
Networks, 2/E, Phi Learning Pvt Ltd, 2009,
ISBN-13: 978-8120330191
Kaveh Pahlavan, Prashant Krishnamurthy,
Principles of Wireless Networks, Prentice Hall,
2002, ISBN: 0-13-093003-2
1. Problem definition
INSTRUCTIONS FOR 2. Learning objective
WRITING JOURNAL 3. Learning Outcome
4. Related Mathematics
5. State Transition Diagram
6. Concepts related Theory
7. Program code with proper documentation.
8. Output of program. Conclusion and applications
(the verification and testing of outcomes).

P:F-LTL-UG/03/R1 Page 51
Aim :

Design and implement a network of 3 servers and multiple users using wireless
networks over ns-3 simulator.

Prerequisites :

Programming features in C++ or Python

Object oriented programming concepts

Learning Objectives :

To understand the basic working of ns-3 simulator

To understand the working of wireless networks and designing them

Learning Outcome :After successfully completing this assignment, you


should be able to Design and implement any network on the ns-3 simulator.

Related Mathematics

Mathematical Model
Let us consider S as a system of designing a network

S= {S, I, Fs, O, DD, NDD| }

Where, S= Start state

I= Set of inputs = {}

Where = set of servers like { , , }


= set of clients like {}
= connectivity whether TCP/IP or UDP
= data packets,}

DD = Deterministic data;

NDD = Non deterministic data;

Operations performed:

{ PointToPointChannel( ), SetConstantPosition( ), WifiChannel( ),


NetDeviceContainer( ), InternetStackHelper( ), Ipv4AddressHelper( ),
UdpEchoClientApplication( ), UdpEchoServerApplication( ) }

PointToPointChannel( ) = establishes a point to point connection


between two nodes.
WifiChannel( ) = establishes a wife connection between two nodes.

P:F-LTL-UG/03/R1 Page 52
SetConstantPosition( ) = sets a position of nodes on the animator.
NetDeviceContainer( ) = has list of networking devices which can be
used.
InternetStackHelper( ) = has list of protocols which can be used.
Ipv4AddressHelper( ) = setting up of Ipv4 connectivity.
UdpEchoClientApplication( ) = applications list for client.
UdpEchoServerApplication( ) = applications list for server.

= Final state
O= {O1, O2, O3, On |O outcome of operations performed by the system
which displays transmission of packets from intended nodes}

Success:
Finally, we can design and implement desired network after performing all
operations defined above.
Failure:
Nodes will not be able to transfer data packets in animator window.

P:F-LTL-UG/03/R1 Page 53
State Transition Diagram

START

Write a program of wireless network comprising of 3 servers and clients

Establish the connection between them

Execute code $ ./waf--run progname (for c++)

$ ./waf --pyrun examples/wireless/progname.py (for python)

Check output

Check / Modify

End

Concepts related Theory

NS-3 is a discrete-event network simulator, targeted primarily for research and


educational use. NS-3 is free software, licensed under the GNU GPLv2 license,
and is publicly available for research, development, and use.

A wireless network is any type of computer network that uses wireless data
connections for connecting network nodes.

Wireless networking is a method by which homes, telecommunications networks


and enterprise (business) installations avoid the costly process of introducing
cables into a building, or as a connection between various equipment locations.
Wireless telecommunications networks are generally implemented and
administered using radio communication. This implementation takes place at the
physical level (layer) of the OSI model network structure.
P:F-LTL-UG/03/R1 Page 54
Examples of wireless networks include cell phone networks, Wi-Fi local networks
and terrestrial microwave networks.

Fig: Wireless Network

Types of wireless networks:

Wireless PAN- Wireless personal area networks (WPANs)


interconnect devices within a relatively small area, that is generally
within a person's reach. For example, both Bluetooth radio and
invisible infrared light provides a WPAN for interconnecting a headset
to a laptop.

Wireless LAN- A wireless local area network (WLAN) links two or


more devices over a short distance using a wireless distribution
method, usually providing a connection through an access point for
Internet access.

Wireless mesh network- A wireless mesh network is a wireless


network made up of radio nodes organized in a mesh topology.

Wireless MAN- Wireless metropolitan area networks are a type of


wireless network that connects several wireless LANs.

P:F-LTL-UG/03/R1 Page 55
Wireless WAN- Wireless wide area networks are wireless networks
that typically cover large areas, such as between neighboring towns
and cities, or city and suburb.

Cellular network- A cellular network or mobile network is a radio


network distributed over land areas called cells, each served by at least
one fixed-location transceiver, known as a cell site or base station.

Global area network- A global area network (GAN) is a network used


for supporting mobile across an arbitrary number of wireless LANs,
satellite coverage areas, etc.

Space network- Space networks are networks used for communication


between spacecraft, usually in the vicinity of the Earth. The example of
this is NASA's Space Network.

Difficulties in Wireless Networks:

Interference

Absorption and reflection

Multipath fading

Hidden node problem

Shared resource problem

Capacity

Conclusion:

Thus, after successfully completing this assignment, you should be able to


understand & implement networks in NS3.

P:F-LTL-UG/03/R1 Page 56
DMTA Revised on: 15/06/2016

TITLE Clustering Technique

PROBLEM Implement a simple approach for k-means/ k-medoids


STATEMENT clustering using C++.
/DEFINITION
OBJECTIVE Objective is to minimize variance between instances
within cluster.
Operating Systems (64-Bit)64-BIT Fedora 17 or latest
64-BIT Update of Equivalent Open source OS or latest
S/W PACKAGES AND
64-BIT Version and update of Microsoft Windows 7
HARDWARE Operating System onwards
APPARATUS USED
2. Programming Tools (64-Bit) Latest Open source
update of Eclipse Programming frame work, GTK+
REFERENCES 1 Saumen Charkrobarti, Mining the Web Discovering
Knowledge from Hypertext Data". Pie, Morgan
Kaufmann Publishers 3rd edition.
2 Parag Kulkarni, Sarang Joshi, Meta Brown et. al.,
"Mining Unstructured Data: A Big Data Perspective",
PHI, 2015, ISBN: 978-81-203-5116-5
3 M. Dunham, Data mining: Introductory and
Advanced topics", Pearson Education, 2003.
1. Problem definition
INSTRUCTIONS FOR 2. Learning objective
WRITING JOURNAL 3. Learning Outcome
4. Related Mathematics
5. Class Diagram
6. Concepts related Theory
7. Program code with proper documentation.
8. Output of program. Conclusion and applications
(the verification and testing of outcomes).

P:F-LTL-UG/03/R1 Page 57
Aim

Write a program using C/C++ a simple approach for k-means/ k-medoids clustering

Prerequisites

Basic programming in C++

Learning Objectives

To understand Data Mining Concepts.

To develop problem solving abilities using Mathematical Modelling

To develop time and space efficient algorithms

Learning Outcome

After successfully completing this assignment, you should be able to Understand


& Implement efficient design, analysis and testing of algorithmic assignments.

Related Mathematics

Mathematical Model
Let us consider S as a start state with initial instances of data.

Identify the inputs

S = Start state

X = { x1, x2, x3, ..., xn | 'X' n instances of data.}

A = { a1, a2, a3, ..., ap | A p attributes of each instance X. }

K = {k | k N, no of clusters.}

I = {X, K}

DD = Deterministic data;

NDD = Non deterministic data;

C = { C1, C2, C3, ..., CK }

Operations performed :

{ initialize_cluster(X, Y), assign_cluster(X, Y), update_cluster(X, Y) }

initialize_cluster(X) = C; randomly selecting k cluster centres.


C = { m | m is the center of cluster C}

P:F-LTL-UG/03/R1 Page 58
assign_cluster(X, C) = B'; calculate the nearest cluster center to each
Xi.
Cj { mj | center of cluster Cj }
if min{ d(Xi , m1), d(Xi , m2), , d(Xi , mk) } = d(Xi , mj)
then Xi mj
Xj { Xj,1 , Xj,2 , , Xj,p | p attributes of Xj }
mj { mj,1 , mj,2 , , mj,p | p attributes of mj }
d(Xi , mj) = | Xi,1 mj,1 | + | Xi,2 mj,2 | + + | Xi,p mj,p |
update_cluster(C) = C'; calculate the new cluster center.
= {m | no of instances within cluster}
Iteration of cluster assigning procedure occurs till terminating
condition is met.
Termination condition could be maximum number of iteration to meet
or less cluster variance.
Output:

O= {C1, C2, C3, CK |O outcome of operations performed by the system k


clusters}

Hence final S will comprise of:

S= {S, I, X, K, C, Fs, O, DD, NDD | }

Success: Finally, we can partition all instances into k - clusters successfully.

Failure: Mismatched, incomplete partitioning of instances into k - clusters.

Concepts related Theory

Eucledian distance is used to find distance between instance of data and cluster
center. Cluster center is updated by taking mean between instances of data within
cluster.

Conclusion:

Thus, after successfully completing this assignment, you should be able to understand
& Implement k - mean clustering technique to partition instance data into k clusters in
C++.

P:F-LTL-UG/03/R1 Page 59
ACP Revised on: 15/06/2016

TITLE Multiply 64-bit numbers in Java using shared memory


PROBLEM Write a java program to multiply 64-bit numbers using shared
STATEMENT memory, java collection framework and java utilities.
/DEFINITION
OBJECTIVE To use shared memory in Java
To use Java utility class
To perform 64-bit numbers multiplication
S/W 64-bit Fedora or equivalent OS with 64-bit Intel-i5/ i7 or latest
PACKAGES higher processor computers, Eclipse IDE
AND
HARDWARE
APPARATUS
USED
REFERENCES Java Complete Reference by Herbert Schiedlt
https://docs.oracle.com/javase/tutorial/collections/intro/
http://whatis.techtarget.com/definition/shared-memory
http://stackoverflow.com/questions/1491519/any-concept-
of-shared-memory-in-java
INSTRUCTION 1. Problem definition
S FOR 2. Learning objective
WRITING 3. Learning Outcome
JOURNAL
4. Related Mathematics
5. Class Diagram
6. Concepts related Theory
7. Program code with proper documentation.
8. Output of program. Conclusion and applications
(the verification and testing of outcomes).

P:F-LTL-UG/03/R1 Page 60
Aim

Write a java program to multiply 64-bit numbers using shared memory, java
collection framework and java utilities.

Prerequisites

Concept of shared memory in Java


Knowledge of object oriented programming features

Learning Objectives

To understand working of shared memory

To understand Java utility classes

Learning Outcome

After successfully completing this assignment, student shall be able to

Implement 64-bit number multiplication in Java using shared memory and


utility classes

Related Mathematics

Mathematical Model
Let

N1 = <b11 b12 b13 b1n1> 1 |N1| 64

N2 = <b21 b22 b23 b2n2> 1 |N2| 64

b1i {0,1}
1i64

b2i {0,1}
1i64

B64 = { {0,1}64} BK = { {0,1}K}

MULT: B64 X B64 => B129 such that MULT(X,Y) = X x Y

Success

P:F-LTL-UG/03/R1 Page 61
Students are able to multiply 64 bit number in Java using shared memory
Failure
Incorrect result of multiplication
Concepts related Theory

In computer programming, shared memory is a method by which program


processes can exchange data more quickly than by reading and writing using the
regular operating system services. For example, a client process may have data to
pass to a server process that the server process is to modify and return to the
client. Ordinarily, this would require the client writing to an output file (using the
buffers of the operating system) and the server then reading that file as input from
the buffers to its own work space. Using a designated area of shared memory, the
data can be made directly accessible to both processes without having to use the
system services.

Shared memory is the fastest interprocess communication mechanism. The


operating system maps a memory segment in the address space of several
processes, so that several processes can read and write in that memory segment
without calling operating system functions. However, we need some kind of
synchronization between processes that read and write shared memory. Below fig
1 show shared memory architecture.

Fig 1 Shared memory architecture

In Java, there is no official API to create a shared memory segment. In this case
you need to resort to a helper library/DDL and JNI to use shared memory to have
two Java processes talk to each other.

In practice, this is rarely an issue since Java supports threads, so you can have two
"programs" run in the same Java VM. Those will share the same heap, so

P:F-LTL-UG/03/R1 Page 62
communication will be instantaneous. Plus you can't get errors because of
problems with the shared memory segment.

Class Diagram

JavaMultiplication

+multiplier1, multiplier2

+acceptInput()

+performMultiplication()
Conclusion
+writeToMemoryMapped
File() shall be able to understand shared memory concept & shall be able to
Students
implement 64-bit numbers multiplication in Java.

P:F-LTL-UG/03/R1 Page 63

You might also like