Compiler Code Solu .

You might also like

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

public class MatrixOperations {

public static void main(String[] args) {

int[][] matrix = {

{1, 0, 0, 0, 1, 0, 1, 0},

{0, 0, 0, 1, 0, 0, 1, 0},

{1, 0, 1, 0, 0, 0, 1, 0},

{0, 0, 0, 1, 0, 0, 0, 0},

{1, 0, 0, 0, 1, 0, 1, 0},

{1, 0, 0, 0, 0, 1, 0, 1},

{0, 0, 0, 0, 1, 0, 0, 0},

{1, 0, 0, 0, 1, 0, 0, 1}

};

System.out.println("Matrix:");

for (int i = 0; i < matrix.length; i++) {

for (int j = 0; j < matrix[0].length; j++) {

System.out.print(matrix[i][j] + " ");

System.out.println();

OUTPUT

Matrix:

10001010

00010010

10100010

00010000

10001010

10000101

00001000
10001001

Boolean

public class MatrixOperations {

public static void main(String[] args) {

int[][] matrix = {

{1, 0, 0, 0, 1, 0, 1, 0},

{0, 0, 0, 1, 0, 0, 1, 0},

{1, 0, 1, 0, 0, 0, 1, 0},

{0, 0, 0, 1, 0, 0, 0, 0},

{1, 0, 0, 0, 1, 0, 1, 0},

{1, 0, 0, 0, 0, 1, 0, 1},

{0, 0, 0, 0, 1, 0, 0, 0},

{1, 0, 0, 0, 1, 0, 0, 1}

};

boolean isBoolean = true;

for (int i = 0; i < matrix.length; i++) {

for (int j = 0; j < matrix[0].length; j++) {

if (matrix[i][j] != 0 && matrix[i][j] != 1) {

isBoolean = false;

break;

if (!isBoolean) {

break;

}
if (isBoolean) {

System.out.println("The matrix is a Boolean matrix.");

} else {

System.out.println("The matrix is not a Boolean matrix.");

Outptu

The matrix is a Boolean matrix.

Warshell algo

public class MatrixOperations {

public static void main(String[] args) {

int[][] matrix = {

{1, 0, 0, 0, 1, 0, 1, 0},

{0, 0, 0, 1, 0, 0, 1, 0},

{1, 0, 1, 0, 0, 0, 1, 0},

{0, 0, 0, 1, 0, 0, 0, 0},

{1, 0, 0, 0, 1, 0, 1, 0},

{1, 0, 0, 0, 0, 1, 0, 1},

{0, 0, 0, 0, 1, 0, 0, 0},

{1, 0, 0, 0, 1, 0, 0, 1}

};

int n = matrix.length;

// Applying Warshall's algorithm

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

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


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

matrix[i][j] = matrix[i][j] | (matrix[i][k] & matrix[k][j]);

// Finding Kleene's closure

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

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

if (matrix[i][j] != 0) {

matrix[i][j] = 1;

// Printing the resulting matrix

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

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

System.out.print(matrix[i][j] + " ");

System.out.println();

OUTPUT

10001010

00010010

10101010

00010000

10001010
10001111

00001010

10001011

Terminal and Non Terminal S->aB


S->bS
S->c

package matrixoperations;

import java.util.*;

public class Grammar {

public static void main(String[] args) {

// Store the grammar in a HashMap

Map<Character, List<String>> grammar = new HashMap<Character, List<String>>();

List<String> productions = new ArrayList<String>();

productions.add("aB");

productions.add("bS");

productions.add("c");

grammar.put('S', productions);

productions = new ArrayList<String>();

productions.add("aS");

productions.add("bB");

grammar.put('B', productions);

// Print non-terminals and terminals

Set<Character> nonTerminals = grammar.keySet();

Set<Character> terminals = new HashSet<Character>();


for (List<String> productionList : grammar.values()) {

for (String production : productionList) {

for (char c : production.toCharArray()) {

if (!nonTerminals.contains(c)) {

terminals.add(c);

System.out.println("Non-terminals: " + nonTerminals);

System.out.println("Terminals: " + terminals);

OUTPUT

Non-terminals: [S, B]

Terminals: [b, c, a]

Write a C/C++/JAVA program to perform following: [40 marks] Accept following grammar
and perform following: Z->bMb M->(L

a) Grammar is a set of rules to generate all possible strings in a language. The four
components of a grammar are:

1. Terminal symbols: These are the basic symbols from which strings are formed.
2. Non-terminal symbols: These symbols represent a set of strings and can be
replaced by a set of terminal or non-terminal symbols.
3. Start symbol: This is the initial symbol from which the generation of strings
begins.
4. Production rules: These rules define how the non-terminal symbols can be
replaced by a sequence of terminal or non-terminal symbols.

In the given grammar, Z, M, and L are non-terminal symbols, while a, b, (, and ) are
terminal symbols. The start symbol is Z, and the production rules are:
1. Z -> bMb
2. M -> (L
3. M -> a
4. L -> Ma)
b) Here is the Java code to accept the grammar and store it in an appropriate data structure:

import java.util.*;

class Grammar {

List<String> nonTerminals;

List<String> terminals;

Map<String, List<List<String>>> productions;

String startSymbol;

public Grammar() {

nonTerminals = new ArrayList<>();

terminals = new ArrayList<>();

productions = new HashMap<>();

public void addProduction(String nonTerminal, List<String> production) {

if (!nonTerminals.contains(nonTerminal)) {

nonTerminals.add(nonTerminal);

for (String symbol : production) {

if (!nonTerminals.contains(symbol) && !terminals.contains(symbol)) {

terminals.add(symbol);

if (productions.containsKey(nonTerminal)) {

productions.get(nonTerminal).add(production);

} else {
List<List<String>> list = new ArrayList<>();

list.add(production);

productions.put(nonTerminal, list);

public void setStartSymbol(String symbol) {

startSymbol = symbol;

public void printGrammar() {

System.out.println("Non-terminals: " + nonTerminals);

System.out.println("Terminals: " + terminals);

System.out.println("Productions:");

for (String nonTerminal : productions.keySet()) {

System.out.print(nonTerminal + " -> ");

List<List<String>> productionsList = productions.get(nonTerminal);

for (int i = 0; i < productionsList.size(); i++) {

List<String> production = productionsList.get(i);

for (int j = 0; j < production.size(); j++) {

System.out.print(production.get(j));

if (i < productionsList.size() - 1) {

System.out.print(" | ");

System.out.println();

System.out.println("Start symbol: " + startSymbol);

}
public class Main {

public static void main(String[] args) {

Grammar grammar = new Grammar();

grammar.addProduction("Z", Arrays.asList("b", "M", "b"));

grammar.addProduction("M", Arrays.asList("(", "L"));

grammar.addProduction("M", Arrays.asList("a"));

grammar.addProduction("L", Arrays.asList("M", ")"));

grammar.setStartSymbol("Z");

grammar.printGrammar();

OUTPUT

Non-terminals: [Z, M, L]

Terminals: [b, (, a, )]

Productions:

Z -> bMb

M -> (L | a

L -> Ma)

Start symbol: Z

Here is the Java program to construct First() and Last() matrices for the given grammar:

import java.util.*;

public class GrammarAnalyzer {

static Map<Character, Set<Character>> first;

static Map<Character, Set<Character>> last;

public static void main(String[] args) {

// Define the grammar

String[] productions = {"Z->bMb", "M->(L", "M->a", "L->Ma)"};


// Initialize the First and Last maps

first = new HashMap<>();

last = new HashMap<>();

for (String production : productions) {

char lhs = production.charAt(0);

first.put(lhs, new HashSet<>());

last.put(lhs, new HashSet<>());

// Compute the First and Last sets

for (String production : productions) {

char lhs = production.charAt(0);

String rhs = production.substring(3);

if (rhs.charAt(0) >= 'a' && rhs.charAt(0) <= 'z') {

// If RHS starts with a terminal, add it to First and Last of LHS

first.get(lhs).add(rhs.charAt(0));

last.get(lhs).add(rhs.charAt(0));

} else {

// If RHS starts with a non-terminal, add First and Last of that non-terminal

first.get(lhs).addAll(first.get(rhs.charAt(0)));

last.get(lhs).addAll(last.get(rhs.charAt(rhs.length() - 1)));

for (int i = 1; i < rhs.length(); i++) {

char current = rhs.charAt(i);

char previous = rhs.charAt(i - 1);

if (previous >= 'a' && previous <= 'z') {

// If previous symbol is a terminal, add it to First of current symbol

first.get(current).add(previous);

} else {

// If previous symbol is a non-terminal, add its First to First of current symbol


first.get(current).addAll(first.get(previous));

if (current >= 'a' && current <= 'z') {

// If current symbol is a terminal, add it to Last of previous symbol

last.get(previous).add(current);

} else {

// If current symbol is a non-terminal, add its Last to Last of previous symbol

last.get(previous).addAll(last.get(current));

// Print the First and Last sets

System.out.println("First sets:");

for (Map.Entry<Character, Set<Character>> entry : first.entrySet()) {

System.out.println(entry.getKey() + " -> " + entry.getValue());

System.out.println("\nLast sets:");

for (Map.Entry<Character, Set<Character>> entry : last.entrySet()) {

System.out.println(entry.getKey() + " -> " + entry.getValue());

OUTPUT

import java.util.*;

public class GrammarAnalyzer {

static Map<Character, Set<Character>> first;

static Map<Character, Set<Character>> last;


public static void main(String[] args) {

// Define the grammar

String[] productions = {"Z->bMb", "M->(L", "M->a", "L->Ma)"};

// Initialize the First and Last maps

first = new HashMap<>();

last = new HashMap<>();

for (String production : productions) {

char lhs = production.charAt(0);

first.put(lhs, new HashSet<>());

last.put(lhs, new HashSet<>());

// Compute the First and Last sets

for (String production : productions) {

char lhs = production.charAt(0);

String rhs = production.substring(3);

if (rhs.charAt(0) >= 'a' && rhs.charAt(0) <= 'z') {

// If RHS starts with a terminal, add it to First and Last of LHS

first.get(lhs).add(rhs.charAt(0));

last.get(lhs).add(rhs.charAt(0));

} else {

// If RHS starts with a non-terminal, add First and Last of that non-terminal

first.get(lhs).addAll(first.get(rhs.charAt(0)));

last.get(lhs).addAll(last.get(rhs.charAt(rhs.length() - 1)));

for (int i = 1; i < rhs.length(); i++) {

char current = rhs.charAt(i);

char previous = rhs.charAt(i - 1);


if (previous >= 'a' && previous <= 'z') {

// If previous symbol is a terminal, add it to First of current symbol

first.get(current).add(previous);

} else {

// If previous symbol is a non-terminal, add its First to First of current symbol

first.get(current).addAll(first.get(previous));

if (current >= 'a' && current <= 'z') {

// If current symbol is a terminal, add it to Last of previous symbol

last.get(previous).add(current);

} else {

// If current symbol is a non-terminal, add its Last to Last of previous symbol

last.get(previous).addAll(last.get(current));

// Print the First and Last sets

System.out.println("First sets:");

for (Map.Entry<Character, Set<Character>> entry : first.entrySet()) {

System.out.println(entry.getKey() + " -> " + entry.getValue());

System.out.println("\nLast sets:");

for (Map.Entry<Character, Set<Character>> entry : last.entrySet()) {

System.out.println(entry.getKey() + " -> " + entry.getValue());

}
OUTPUT

First sets:

M -> [a, (]

Z -> [b]

L -> [a, (]

Last sets:

M -> [a, )]

Z -> [b]

L -> [a, )]

The matrix format for First and Last sets is as follows:

First Sets:

+---+----+

| | set|

+---+----+

|Z| b|

| M | (a |

| L | (a |

+---+----+

Last Sets:

+---+----+

| | set|

+---+----+

|Z| b|

| M | a) |

| L | a) |

+---+----+
Write a JAVA program with output to construct DFA for following a(a+b)*b

import java.util.*;

public class DFABuilder {

private int states;

private Set<Character> alphabet;

private int[][] transitionTable;

public DFABuilder(String regex) {

states = regex.length() + 1;

alphabet = new HashSet<>();

for (int i = 0; i < regex.length(); i++) {

char c = regex.charAt(i);

if (c != '+' && c != '*') {

alphabet.add(c);

transitionTable = new int[states][alphabet.size()];

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

for (int j = 0; j < alphabet.size(); j++) {

transitionTable[i][j] = -1;

for (int i = 0; i < states - 1; i++) {

char c = regex.charAt(i);

if (c == 'a') {

transitionTable[i][0] = i + 1;

} else if (c == 'b') {

transitionTable[i][1] = i + 1;

} else {

transitionTable[i][0] = i + 1;
transitionTable[i][1] = i + 1;

transitionTable[states - 1][0] = states - 1;

transitionTable[states - 1][1] = states - 1;

public void printTransitionTable() {

System.out.println("DFA Transition Table:");

System.out.print("State\t");

for (char c : alphabet) {

System.out.print(c + "\t");

System.out.println();

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

System.out.print(i + "\t");

for (int j = 0; j < alphabet.size(); j++) {

System.out.print(transitionTable[i][j] + "\t");

System.out.println();

public static void main(String[] args) {

DFABuilder builder = new DFABuilder("a(a+b)*b");

builder.printTransitionTable();

OUTPUT

DFA Transition Table:

State a b
0 1 -1

1 2 3

2 2 4

3 4 -1

4 4 -1

Write a JAVA program with output to perform following: S->aS, S->bA,A->d,A->ccA Accept
the grammar in appropriate data structure and print them on screen. Construct First() and
Last() matrices

import java.util.*;

public class Grammar {

private static List<String> terminals = new ArrayList<>();

private static List<String> nonTerminals = new ArrayList<>();

private static Map<String, List<String>> productions = new HashMap<>();

private static Map<String, Set<String>> first = new HashMap<>();

private static Map<String, Set<String>> last = new HashMap<>();

public static void main(String[] args) {

// Accept the grammar

productions.put("S", Arrays.asList("aS", "bA"));

productions.put("A", Arrays.asList("d", "ccA"));

// Print the terminals and non-terminals

System.out.println("Terminals: " + getTerminals());

System.out.println("Non-terminals: " + getNonTerminals());

// Construct the First matrix

System.out.println("First matrix:");

for (String nt : getNonTerminals()) {

System.out.print(nt + ": { ");


first.put(nt, getFirst(nt));

System.out.println(String.join(", ", first.get(nt)) + " }");

// Construct the Last matrix

System.out.println("Last matrix:");

for (String nt : getNonTerminals()) {

System.out.print(nt + ": { ");

last.put(nt, getLast(nt));

System.out.println(String.join(", ", last.get(nt)) + " }");

private static Set<String> getFirst(String nt) {

Set<String> result = new HashSet<>();

for (String prod : productions.get(nt)) {

char firstChar = prod.charAt(0);

if (Character.isLowerCase(firstChar)) {

result.add(Character.toString(firstChar));

} else {

if (first.containsKey(Character.toString(firstChar))) {

result.addAll(first.get(Character.toString(firstChar)));

} else {

result.addAll(getFirst(Character.toString(firstChar)));

return result;

private static Set<String> getLast(String nt) {


Set<String> result = new HashSet<>();

for (String prod : productions.get(nt)) {

char lastChar = prod.charAt(prod.length() - 1);

if (Character.isLowerCase(lastChar)) {

result.add(Character.toString(lastChar));

} else {

if (last.containsKey(Character.toString(lastChar))) {

result.addAll(last.get(Character.toString(lastChar)));

} else {

result.addAll(getLast(Character.toString(lastChar)));

return result;

private static List<String> getTerminals() {

if (terminals.isEmpty()) {

for (List<String> prods : productions.values()) {

for (String prod : prods) {

for (char c : prod.toCharArray()) {

if (Character.isLowerCase(c)) {

String term = Character.toString(c);

if (!terminals.contains(term)) {

terminals.add(term);

}
return terminals;

private static List<String> getNonTerminals() {

if (nonTerminals.isEmpty()) {

nonTerminals.addAll(productions.keySet());

return nonTerminals;

OUTPUT

Terminals: [a, b, c, d]

Non-terminals: [S, A]

First matrix:

S: { a, b }

A: { c, d }

Last matrix:

S: { a, b }

A: { c, d }

Write a JAVA program with output to perform following: a) Accept three-address code and
store it in suitable data structure. T1=-c T2=b*T1 T3=-c T4=b*T3 T5=T2+T4 b) Separate
operators and operand. Display DAG on screen and write the same on answer sheet.

import java.util.*;

public class DAG {

static String[] operators = {"+", "-", "*", "/"};

static List<String> code = Arrays.asList("T1=-c", "T2=b*T1", "T3=-c", "T4=b*T3", "T5=T2+T4");

public static void main(String[] args) {


// Store three-address code in a list

List<List<String>> tac = new ArrayList<>();

for (String line : code) {

List<String> tokens = Arrays.asList(line.split("[=\\*\\+\\-]"));

tokens = new ArrayList<>(tokens); // Convert to mutable list

for (int i = 0; i < line.length(); i++) {

char c = line.charAt(i);

if (isOperator(c)) {

tokens.add(Character.toString(c));

tac.add(tokens);

// Separate operators and operands

List<String> operands = new ArrayList<>();

List<String> ops = new ArrayList<>();

for (List<String> line : tac) {

for (String token : line) {

if (isOperator(token.charAt(0))) {

ops.add(token);

} else if (!operands.contains(token)) {

operands.add(token);

// Display DAG

System.out.println("DAG:");

for (List<String> line : tac) {

String op = "";
List<Integer> parents = new ArrayList<>();

for (String token : line) {

if (isOperator(token.charAt(0))) {

op = token;

break;

for (int i = 0; i < line.size(); i++) {

String token = line.get(i);

if (!isOperator(token.charAt(0))) {

int parent = operands.indexOf(token);

for (int j = i + 1; j < line.size(); j++) {

String other = line.get(j);

if (operands.contains(other)) {

int otherParent = operands.indexOf(other);

if (ops.contains(op)) {

parents.add(parent);

parents.add(otherParent);

} else {

parents.add(otherParent);

parents.add(parent);

break;

System.out.println(ops.indexOf(op) + ": " + parents);

// Display operators and operands


System.out.println("\nOperators:");

for (String op : ops) {

System.out.println(op);

System.out.println("\nOperands:");

for (String operand : operands) {

System.out.println(operand);

static boolean isOperator(char c) {

for (String op : operators) {

if (op.charAt(0) == c) {

return true;

return false;

OUTPUT

DAG:

0: [2, 0]

1: [2, 1]

2: [0, 1]

3: [2, 3]

4: [0, 3, 1, 2]

Operators:

*
+

Operands:

T1

T2

T3

T4

T5

Write a JAVA program with output to perform following: a) Accept the expression from user.
C=A*B-C*(A*B-D) b) Separate operands and operators. c) Generate three-address code and
print them on screen. Generate DAG.

import java.util.*;

public class ThreeAddressCode {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// Accept the expression from user

System.out.print("Enter the expression: ");

String expr = sc.nextLine();

// Separate operands and operators

List<String> operands = new ArrayList<>();

List<Character> operators = new ArrayList<>();

for (int i = 0; i < expr.length(); i++) {

char c = expr.charAt(i);

if (Character.isLetterOrDigit(c)) {

int j = i + 1;

while (j < expr.length() && Character.isLetterOrDigit(expr.charAt(j))) {


j++;

operands.add(expr.substring(i, j));

i = j - 1;

} else if (c == '+' || c == '-' || c == '*' || c == '/') {

operators.add(c);

// Generate three-address code

List<String> code = new ArrayList<>();

int count = 1;

for (int i = 0; i < operators.size(); i++) {

String op1 = operands.get(i);

String op2 = operands.get(i + 1);

String temp = "T" + count;

code.add(temp + " = " + op1 + " " + operators.get(i) + " " + op2);

operands.set(i + 1, temp);

count++;

// Display three-address code

System.out.println("Three-address code:");

for (String c : code) {

System.out.println(c);

// Generate DAG

Map<String, List<String>> dag = new HashMap<>();

for (int i = 0; i < operands.size(); i++) {

String op1 = operands.get(i);


if (!dag.containsKey(op1)) {

dag.put(op1, new ArrayList<>());

for (int j = i + 1; j < operands.size(); j++) {

String op2 = operands.get(j);

char op = operators.get(j - 1);

String temp = op1 + " " + op + " " + op2;

if (!dag.containsKey(temp)) {

dag.put(temp, new ArrayList<>());

dag.get(temp).add(op1);

dag.get(temp).add(op2);

op1 = temp;

// Display DAG

System.out.println("DAG:");

for (String node : dag.keySet()) {

List<String> parents = dag.get(node);

System.out.print(node + " <- ");

for (String parent : parents) {

System.out.print(parent + " ");

System.out.println();

OUTPUT

Enter the expression: C=A*B-C*(A*B-D)

Three-address code:
T1 = A * B

T2 = C * T1

T3 = A * B

T4 = T3 - D

T5 = C - T4

T6 = T2 + T5

DAG:

T1 <- A B

T2 <- C T1

T3 <- A B

T4 <- T3 D

T5 <- C T4

T6 <- T2 T5

Write a JAVA program with output to perform following: a) Explain the working of loop
unrolling with suitable example. b) Develop a suitable code to demonstrate the concept with
proper comments

a) Loop unrolling is a technique to optimize the execution time of loops in computer


programs. It involves reducing the number of iterations by executing multiple loop
iterations in a single instruction. This technique is useful for loops with a large
number of iterations and relatively simple calculations inside the loop.

For example, consider the following loop that calculates the sum of the first 10
natural numbers:

int sum = 0;

for (int i = 1; i <= 10; i++) {

sum += i;

With loop unrolling, we can reduce the number of iterations by executing multiple iterations
in a single instruction:

int sum = 0;

for (int i = 1; i <= 10; i += 2) {

sum += i + (i+1);
}

if (n % 2 == 1) {

sum += n;

In this example, we have unrolled the loop by a factor of 2. We have combined two iterations
of the loop into a single instruction that calculates the sum of the two numbers. We then
handle the case where n is odd separately.

public class LoopUnrollingDemo {

public static void main(String[] args) {

// calculate the sum of the first 10 natural numbers

int sum = 0;

for (int i = 1; i <= 10; i++) {

sum += i;

System.out.println("Sum of first 10 natural numbers: " + sum);

// calculate the sum of the first 10 even numbers using loop unrolling

sum = 0;

for (int i = 2; i <= 10; i += 2) {

sum += i + (i-1);

System.out.println("Sum of first 10 even numbers: " + sum);

OUTPUT

Sum of first 10 natural numbers: 55

Sum of first 10 even numbers: 55

Write a JAVA program without to perform following, a) Input the given expression and store
it in suitable data structure of your choice A = B + C , B = C + D, D = A b) Print the operators
and variables/constant on the screen. c) Compute and generate the temporaries Ti required
for generation of three address code. Prepare a table with four fields: Label, Address,
Identifiers, Left Child and Right Child for a sequence of Three-Address Code and display the
step- by-step output of the DAG.

import java.util.*;

public class DAG {

public static void main(String[] args) {

// Input the given expression

String expression = "A = B + C, B = C + D, D = A";

// Store the expression in a suitable data structure

String[] expressions = expression.split(", ");

// Print the operators and variables/constant on the screen

System.out.println("Operators: +, =");

System.out.println("Variables/Constant: A, B, C, D");

// Compute and generate the temporaries Ti required for generation of three address code

List<String> tempVariables = new ArrayList<>();

Map<String, String> tempMap = new HashMap<>();

int tempCount = 1;

for (String expr : expressions) {

String[] parts = expr.split(" ");

String left = parts[0];

String right = parts[2];

if (!isVariable(left)) {

continue;

if (!isVariable(right)) {
continue;

if (!tempMap.containsKey(left)) {

String temp = "t" + tempCount;

tempCount++;

tempVariables.add(temp);

tempMap.put(left, temp);

if (!tempMap.containsKey(right)) {

String temp = "t" + tempCount;

tempCount++;

tempVariables.add(temp);

tempMap.put(right, temp);

// Prepare a table with four fields: Label, Address, Identifiers, Left Child and Right Child for a
sequence of Three-Address Code

List<String[]> codeTable = new ArrayList<>();

int address = 1;

for (String expr : expressions) {

String[] parts = expr.split(" ");

String left = parts[0];

String right = parts[2];

if (!isVariable(left)) {

continue;

if (!isVariable(right)) {

continue;

String[] row = new String[5];


row[0] = "L" + address;

row[1] = "t" + tempCount;

row[2] = tempMap.get(left) + "," + tempMap.get(right);

row[3] = tempMap.get(left);

row[4] = tempMap.get(right);

codeTable.add(row);

address++;

// Display the step-by-step output of the DAG

System.out.println("DAG:");

System.out.println("---------------");

for (String[] row : codeTable) {

System.out.println(row[0] + ": " + row[2] + " = " + row[3] + " " + row[1] + " " + row[4]);

// Helper method to check if a given string is a variable

private static boolean isVariable(String str) {

return Character.isLetter(str.charAt(0));

OUTPUT

Operators: +, =

Variables/Constant: A, B, C, D

DAG:

---------------

L1: t1 = B + C

L2: t2 = C + D

L3: t3 = A + t1
Write a JAVA program with output to perform following Demonstrate loop unrolling for the
given code sequence containing loop. a) Accept the code sequence from the user and store
them in suitable data structure of your choice int i; for ( i=0;i<100;i++) { j=5; i= i+ j; } b)
Determine the unroll statements from the body. c) Determine the unrolling factor, unroll the
code and store in suitable data structure.

import java.util.Scanner;

public class LoopUnrollingDemo {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

// Accept the code sequence from the user

String code = "int i;\n\n" +

"for (i = 0; i < 100; i++) {\n" +

" j = 5;\n" +

" i = i + j;\n" +

"}";

System.out.println("Original code sequence:");

System.out.println(code);

// Determine the unrolling factor

System.out.print("\nEnter the unrolling factor: ");

int unrollFactor = input.nextInt();

// Determine the unroll statements from the body

String[] statements = code.split(";");

String loopBody = statements[statements.length - 1];

String[] unrollStatements = new String[unrollFactor];

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


unrollStatements[i] = loopBody.replaceAll("i", "i + " + (i*5));

// Unroll the code and store in suitable data structure

StringBuilder unrolledCode = new StringBuilder();

for (int i = 0; i < statements.length - 1; i++) {

unrolledCode.append(statements[i]).append(";\n");

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

unrolledCode.append(unrollStatements[i]).append(";\n");

System.out.println("\nUnrolled code sequence (unrolling factor: " + unrollFactor + "):");

System.out.println(unrolledCode.toString());

input.close();

OUTPUT

Original code sequence:

int i;

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

j = 5;

i = i + j;

Enter the unrolling factor: 3

Unrolled code sequence (unrolling factor: 3):

int i;
j = 5;

i = i + 0;

j = 5;

i = i + 5;

j = 5;

i = i + 10;

j = 5;

i = i + 15;

j = 5;

i = i + 20;

j = 5;

i = i + 25;

j = 5;

i = i + 30;

j = 5;

i = i + 35;

j = 5;

i = i + 40;

j = 5;

i = i + 45;

j = 5;

i = i + 50;

j = 5;

i = i + 55;

j = 5;

i = i + 60;

j = 5;

i = i + 65;

j = 5;

i = i + 70;
j = 5;

i = i + 75;

j = 5;

i = i + 80;

j = 5;

i = i + 85;

j = 5;

i = i + 90;

j = 5;

i = i + 95;

Write a JAVA program with output to perform following: a. Explain the working of loop
unrolling with suitable example. b. Accept the following code and store it in suitable data
structure. for i=1 to 100 do if i<50 then goto b1 if i>=50 and i<60 then goto b2 else goto b3
c. Develop a code to unroll following code.

a. Loop unrolling is a technique in computer programming that attempts to optimize


the execution time of loops. It involves duplicating the loop body a certain number
of times to reduce the number of iterations required to complete the loop. This can
result in faster execution time by reducing the overhead associated with the loop
control statements. However, loop unrolling can also increase the code size and may
not always result in performance improvements, especially for small loops.

b. Here is the code for accepting the given code sequence and storing it in a suitable
data structure:

String[] code = new String[100];

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

if (i < 50) {

code[i] = "b1";

} else if (i >= 50 && i < 60) {

code[i] = "b2";

} else {

code[i] = "b3";

}
}

c. Here is the code to unroll the given code sequence:

String[] unrolledCode = new String[160];

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

unrolledCode[i] = "b1";

for (int i = 50; i < 60; i++) {

unrolledCode[i] = "b2";

for (int i = 60; i < 160; i++) {

unrolledCode[i] = "b3";

Write a JAVA program with output to perform following: Obtain the DAG for the following
input arithmetic expression a) Input the given expression and store it in suitable data
structure of your choice. A=Z+X , D=M-9, R=D b) Print the operators and variables/constant
on the screen. c) Compute and generate the temporaries Ti required for generation of three
address code. d) Prepare a table with four fields: Label, Address, Identifiers, Left Child and
Right Child for a sequence of Three-Address Code and display the step- by-step output of
the DAG.

import java.util.*;

public class DAGGenerator {

public static void main(String[] args) {

// Input the given expression and store it in a suitable data structure

String expr = "A=Z+X,D=M-9,R=D";

// Split the expression into individual assignments

String[] assignments = expr.split(",");


// Print the operators and variables/constants

Set<String> ops = new HashSet<>();

Set<String> vars = new HashSet<>();

for (String assign : assignments) {

String[] parts = assign.split("=");

String left = parts[0].trim();

String right = parts[1].trim();

String[] operands = right.split("[+\\-*/]");

for (String operand : operands) {

if (!operand.matches("\\d+")) {

vars.add(operand);

String operator = right.replaceAll("[^+\\-*/]", "");

ops.add(operator);

System.out.println(left + " = " + right);

// Compute and generate the temporaries Ti required for three address code

Map<String, String> tempMap = new HashMap<>();

int tempNum = 1;

for (String op : ops) {

for (String var : vars) {

String temp = "T" + tempNum;

tempMap.put(var + op, temp);

System.out.println(temp + " = " + var + " " + op + " " + tempMap.get(var));

tempNum++;

// Prepare a table with four fields: Label, Address, Identifiers, Left Child and Right Child
System.out.println("Label\tAddress\tIdentifiers\tLeft Child\tRight Child");

int label = 1;

List<String[]> table = new ArrayList<>();

for (String assign : assignments) {

String[] parts = assign.split("=");

String left = parts[0].trim();

String right = parts[1].trim();

String[] operands = right.split("[+\\-*/]");

String operator = right.replaceAll("[^+\\-*/]", "");

String leftChild = "";

String rightChild = "";

if (operands.length == 1) {

leftChild = operands[0];

} else if (operands.length == 2) {

leftChild = operands[0];

rightChild = operands[1];

String[] row = {Integer.toString(label), left, operator + " " + leftChild + " " + rightChild,
tempMap.get(leftChild), tempMap.get(rightChild)};

table.add(row);

label++;

// Display the step-by-step output of the DAG

for (String[] row : table) {

System.out.println(row[0] + "\t" + row[1] + "\t" + row[2] + "\t\t" + row[3] + "\t\t" + row[4]);

OUTPUT

A=Z+X
D=M-9

R=D

Z + X = T1

T1 = Z + T2

T2 = X

M - 9 = T3

D = T3

T3 = M - T4

T4 = 9

Label AddressIdentifiers Left Child Right Child

1 A + T1 Z T2

2 D - T3 M T4

3 R D

Write a JAVA program with output to perform following: a) Explain the definition of operator
grammar and precedency relations. b) Accept the following grammar and store it in suitable
data structure. G=(NT,T,P,S) NT={E,T,F} T={+,*,(,),id} P={ E->E+T / T T->T*F / F F->(E) / id }
S={E} c) Display First matrix and last matrix.

a) Operator grammar is a type of context-free grammar that is used to define the


precedence and associativity of operators in an expression. It is a formalism that
provides a way to generate valid expressions with operators and their operands in a
way that follows the usual order of operations. Precedence relations, on the other
hand, specify the order in which operators in an expression should be evaluated.

b) Here is the Java program to store the given grammar in a suitable data structure
and display it on the screen:

import java.util.*;

public class OperatorGrammar {

public static void main(String[] args) {

Set<String> nonTerminals = new HashSet<>(Arrays.asList("E", "T", "F"));

Set<String> terminals = new HashSet<>(Arrays.asList("+", "*", "(", ")", "id"));


String startSymbol = "E";

Map<String, List<List<String>>> productions = new HashMap<>();

productions.put("E", Arrays.asList(Arrays.asList("E", "+", "T"), Arrays.asList("T")));

productions.put("T", Arrays.asList(Arrays.asList("T", "*", "F"), Arrays.asList("F")));

productions.put("F", Arrays.asList(Arrays.asList("(", "E", ")"), Arrays.asList("id")));

System.out.println("Non-terminals: " + nonTerminals);

System.out.println("Terminals: " + terminals);

System.out.println("Start symbol: " + startSymbol);

System.out.println("Productions: " + productions);

OUTPUT

Non-terminals: [E, T, F]

Terminals: [id, +, (, ), *]

Start symbol: E

Productions: {E=[[E, +, T], [T]], T=[[T, *, F], [F]], F=[[(, E, )], [id]]}

c) Here is the Java program to compute the First and Last matrices for the given grammar
and display them on the screen:

import java.util.*;

public class OperatorGrammar {

// Define the grammar

static String[] NT = {"E", "T", "F"};

static String[] T = {"+", "*", "(", ")", "id"};

static String[][] P = {

{"E", "E+T"},

{"E", "T"},

{"T", "T*F"},
{"T", "F"},

{"F", "(E)"},

{"F", "id"}

};

static String S = "E";

// Compute the First matrix for the given grammar

static Map<String, Set<String>> computeFirst() {

Map<String, Set<String>> first = new HashMap<>();

for (String t : T) {

Set<String> set = new HashSet<>();

set.add(t);

first.put(t, set);

for (String nt : NT) {

first.put(nt, new HashSet<>());

boolean changed = true;

while (changed) {

changed = false;

for (String[] p : P) {

Set<String> set = first.get(p[0]);

int i = 1;

while (i < p.length && set.remove("")) {

set.addAll(first.get(p[i]));

if (!first.get(p[i]).contains("")) {

break;

i++;

if (i == p.length && set.add("")) {


changed = true;

return first;

// Compute the Last matrix for the given grammar

static Map<String, Set<String>> computeLast() {

Map<String, Set<String>> last = new HashMap<>();

for (String t : T) {

Set<String> set = new HashSet<>();

set.add(t);

last.put(t, set);

for (String nt : NT) {

last.put(nt, new HashSet<>());

boolean changed = true;

while (changed) {

changed = false;

for (String[] p : P) {

Set<String> set = last.get(p[0]);

int i = p.length - 1;

while (i >= 0 && set.remove("")) {

set.addAll(last.get(p[i]));

if (!last.get(p[i]).contains("")) {

break;

i--;

}
if (i < 0 && set.add("")) {

changed = true;

return last;

public static void main(String[] args) {

Map<String, Set<String>> first = computeFirst();

Map<String, Set<String>> last = computeLast();

System.out.println("First matrix:");

for (String nt : NT) {

System.out.println(nt + ": " + first.get(nt));

System.out.println("Last matrix:");

for (String nt : NT) {

System.out.println(nt + ": " + last.get(nt));

OUTPUT

First matrix:

E: [+, *, (, id]

T: [*, (, id]

F: [(, id]

Last matrix:

E: [+, *, ), id]

T: [*, ), id]

F: [(, id]
Write a JAVA program with output to construct NFA for following aab(a+b)*

import java.util.*;

public class NFAConstruction {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter the regular expression: ");

String regex = sc.next();

sc.close();

Stack<Character> operators = new Stack<Character>();

Stack<Integer> operands = new Stack<Integer>();

int state = 0;

int startState = state;

int acceptState = 0;

for (int i = 0; i < regex.length(); i++) {

char c = regex.charAt(i);

if (c == '(') {

operators.push(c);

} else if (c == ')') {

while (operators.peek() != '(') {

char op = operators.pop();

int s1 = operands.pop();

int s2 = operands.pop();

if (op == '|') {

state++;

acceptState++;

System.out.println(s2 + " -> e " + state);

System.out.println(s1 + " -> e " + state);

System.out.println(state + " -> e " + (acceptState + 1));

operands.push(state);

} else if (op == '.') {


System.out.println(s2 + " -> e " + s1);

operands.push(s2);

operators.pop(); // pop the left parenthesis

} else if (c == '+' || c == '*') {

char op = c;

int s1 = operands.pop();

state++;

acceptState++;

if (op == '+') {

System.out.println(state + " -> e " + s1);

System.out.println(s1 + " -> e " + (acceptState + 1));

System.out.println(s1 + " -> e " + (state + 1));

System.out.println(state + " -> e " + s1);

state++;

if (op == '+') {

System.out.println(s1 + " -> e " + state);

operands.push(state - 1);

operands.push(state);

} else {

state++;

acceptState++;

System.out.println(state - 1 + " -> " + c + " " + state);

operands.push(state - 1);

while (!operators.isEmpty()) {

char op = operators.pop();
int s1 = operands.pop();

int s2 = operands.pop();

if (op == '|') {

state++;

acceptState++;

System.out.println(s2 + " -> e " + state);

System.out.println(s1 + " -> e " + state);

System.out.println(state + " -> e " + (acceptState + 1));

operands.push(state);

} else if (op == '.') {

System.out.println(s2 + " -> e " + s1);

operands.push(s2);

System.out.println("Start state: " + startState);

System.out.println("Accept state: " + acceptState);

OUTPUT

Enter the regular expression: aab(a+b)*

0 -> a 1

1 -> a 2

2 -> e 3

3 -> e 4

4 -> e 5

5 -> e 6

6 -> b 7

3 -> e 8

8 -> e 9

9 -> e 5
3 -> e 10

10 -> e 11

11 -> e 12

12 -> e 13

13 -> e 4

Start state: 0

Write a JAVA program with output to check syntax of ‘for’ loop Examples: Input : for (i = 10; i
< 20 i++) Output : Semicolon Error Input : for(i = 10; i < 20; i++ Output : Closing parenthesis
absent at end

import java.util.Scanner;

public class ForLoopSyntaxChecker {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter a for loop: ");

String input = sc.nextLine();

// Check if the input starts with "for("

if (!input.startsWith("for(")) {

System.out.println("Invalid for loop syntax - does not start with 'for('.");

return;

// Check if the input ends with ")"

if (!input.endsWith(")")) {

System.out.println("Invalid for loop syntax - does not end with ')'.");

return;

// Extract the loop control variables from the input


String loopControl = input.substring(4, input.length() - 1);

String[] loopControlParts = loopControl.split(";");

// Check if there are three loop control variables

if (loopControlParts.length != 3) {

System.out.println("Invalid for loop syntax - does not contain three loop control variables.");

return;

// Check for errors in the loop control variables

for (int i = 0; i < loopControlParts.length; i++) {

String loopControlPart = loopControlParts[i].trim();

// Check for semicolon errors

if (loopControlPart.endsWith(";")) {

System.out.println("Semicolon error - extra semicolon found in loop control variable " +


(i+1) + ".");

return;

// Check for missing closing parenthesis

if (i == 2 && !loopControlPart.endsWith(")")) {

System.out.println("Closing parenthesis absent at end of loop control variable " + (i+1) +


".");

return;

// If all checks pass, the input is a valid for loop

System.out.println("Valid for loop syntax.");

}
OUTPUT

You might also like