Vous êtes sur la page 1sur 30

Compiler Construction Experiments

By Ankit Popli

Experiment I
Write a program for dividing the given input program into lexemes. Code: #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int i, j, k, p, c; char s[120], r[100]; char par[6] = {'(', ')', '{', '}', '[', ']'}; char sym[9] = {'.', ';', ':', ',', '<', '>', '?', '$', '#'}; char key[9][10] = {"main", "if", "else", "switch", "void", "do", "while", "for", "return"}; char dat[4][10] = {"int", "float", "char", "double"}; char opr[5] = {'*', '+', '-', '/', '^'}; FILE *fp; printf("\n Enter the file name: "); scanf("%s", s); fp = fopen(s, "r"); c = 0; do { fscanf(fp, "%s", r); for (i = 0; i < 6; i++) if (strchr(r, par[i]) != NULL) printf("\n Paranthesis :%c", par[i]); for (i = 0; i < 9; i++) if (strchr(r, sym[i]) != NULL) printf("\n Symbol :%c", sym[i]); for (i = 0; i < 9; i++) if (strstr(r, key[i]) != NULL) printf("\n Keyword :%s", key[i]); for (i = 0; i < 4; i++) if ((strstr(r, dat[i]) && (!strstr(r, "printf"))) != NULL) { printf("\n Data type :%s", dat[i]); fscanf(fp, "%s", r); printf("\n Identifiers :%s", r); } for (i = 0; i < 5; i++) if (strchr(r, opr[i]) != NULL) printf("\n Operator :%c", opr[i]); p = c; c = ftell(fp); } while (p != c); return 0; }

/** OUTPUT: Enter the file name: test.txt Data type :int Identifiers :main() Paranthesis :{ Data type :int Identifiers :a Symbol :, Symbol :; Operator :+ Symbol :; Keyword :return Symbol :; Paranthesis :} Paranthesis :} test.txt: int main() { int a = 5, b = 3; b = b + a; return b; } */

Experiment II
WAP to implement a Non-deterministic Finite Automata (NFA). Code: import java.util.Scanner; public class NFA { static final int [][]TABLE=new int[][]{{3,0},{2,6},{0,0}}; /** * Transition Table: * | a | b | * q0 | q1,q0 | | * q1 | q1 | q2,q1 | * q2 | | | */ int current_state,next_state; String inputString; public NFA(String inputString) { current_state=0; this.inputString=inputString; } private boolean validate(){ boolean valid = false; char[] toCharArray = inputString.toCharArray(); for(char ch:toCharArray) if(ch!='a' && ch!='b') return valid; int i=0; for(char ch:toCharArray) { i++; next_state = current_state+1; int possible; int possible_next_state; if(ch=='a') possible_next_state = TABLE[current_state][0]; else possible_next_state = TABLE[current_state][1]; possible = possible_next_state>>next_state & 0x1; if(possible==1) current_state++; if(current_state==2) break; } if(current_state==2 && i==inputString.length()) valid=true; return valid; } public static void main(String[] args) {

while(true){ Scanner s= new Scanner(System.in); String nextLine = s.nextLine(); if(nextLine.equalsIgnoreCase("exit")) break; NFA nfa = new NFA(nextLine); boolean validate = nfa.validate(); if(validate) System.out.println("The Input String is Valid for the given NFA!!"); else System.out.println("The Input String is Invalid for the given NFA!!"); } } } OUTPUT: aaab The Input abcba The Input bba The Input aaa The Input abab The Input aaaaab The Input exit

String is Valid for the given NFA!! String is Invalid for the given NFA!! String is Invalid for the given NFA!! String is Invalid for the given NFA!! String is Invalid for the given NFA!! String is Valid for the given NFA!!

Experiment III
Write a program to convert the regular expression to DFA. Code: #include <stdio.h> #include <stdlib.h> typedef struct { int input[2]; } state; void readtt(state *states, int nstates, int ninps) { int state, inp; printf("Enter the state transition:\n"); for (state = 0; state < nstates; state++) for (inp = 0; inp < ninps; inp++) { printf("(state:%d,%d):", state, inp); scanf("%d", &states[state].input[inp]); } } void dfasimul(state *states, int nstates, char *inpstr) { int i, start; start = 0; for (i = 0; inpstr[i] != '\0'; i++) { start = states[start].input[inpstr[i] - '0']; } if (start == -1) { printf("DFA halted"); return; } else if (start == nstates - 1) printf("String is accepted"); else printf("String is not accepted"); } int main() { state states[100]; int nstates, ninps; char inpstr[20]; printf("\nSIMULATION OF DFA"); printf("\n*****************"); printf("\nEnter the no. of states: "); scanf("%d", &nstates); printf("Enter the no.of inputs: "); scanf("%d", &ninps); readtt(states, nstates, ninps); printf("\nInitial state: 0\nFinal state: %d", nstates - 1); printf("\n\nEnter the string: "); scanf("%s", inpstr); dfasimul(states, nstates, inpstr); return 0; }

OUTPUT: SIMULATION OF DFA ***************** Enter the no. of states: 3 Enter the no.of inputs: 2 Enter the state transition: (state:0,0):0 (state:0,1):1 (state:1,0):0 (state:1,1):1 (state:2,0):0 (state:2,1):1 Initial state: 0 Final state: 2 Enter the string: 1001 String is not accepted.

Experiment IV
Write a program to generate the symbol table of the compiler. Code: #include #include #include #include <stdio.h> <stdlib.h> <string.h> <ctype.h>

char key[5][10] = {"int", "float", "char", "double"}; int b[5] = {2, 4, 1, 8}; int main() { int byte; int label; int i; char data[10], sym[10], val[10]; char a[20]; char str; FILE *fp; fp = fopen("sym.c", "w"); printf("Enter valid declarations:\n"); while ((str = getchar()) != '#') { fputc(str, fp); } fclose(fp); fp = fopen("sym.c", "r"); printf("\nSYMBOL TABLE\n"); printf("\nData-type\tIdentifier\tValue\tBytes-occupied\n"); while ((str = fgetc(fp)) != EOF) { i = 0; label = 0; switch (str) { case ';': printf("\n%s\t\t%s\t\t%s\t\t%d", data, sym, val, byte); break; default: if (isalpha(str)) { do { a[i] = str; i++; str = fgetc(fp); } while (isalpha(str) || isalnum(str)); a[i] = '\0'; fseek(fp, -1, 1); for (i = 0; i < 5; i++) { if (strcmp(a, key[i]) == 0) { byte = b[i]; strcpy(data, a); label = 1;

goto aa; } } if (label == 0) { strcpy(sym, a); } } else if (str == '=') { str = fgetc(fp); if (str == '\'') str = fgetc(fp); goto aa; } else aa : if (isdigit(str) || isalpha(str)) { do { a[i] = str; i++; str = fgetc(fp); } while (isdigit(str) || str == '.' || isalpha(str)); a[i] = '\0'; fseek(fp, -1, 1); strcpy(val, a); } } } fclose(fp); }

OUTPUT: Enter valid declarations: int a=5; double d=2; # SYMBOL TABLE Data-type int double Identifier a d Value 5 2 Bytes-occupied 2 8

Experiment V
Write a program to find Leading terminals. Code: #include #include #include #include <stdio.h> <stdlib.h> <string.h> <iostream.h>

void lead(char[]); char a[5][10], temp[10]; int n; int main() { cout << "Enter the no. of productions:"; cin >> n; int i; for (i = 0; i < n; i++) cin >> a[i]; cout << "\nThe production are:"; for (i = 0; i < n; i++) { cout << "\nProduction " << i + 1 << ": "; cout << a[i]; } for (i = 0; i < n; i++) { cout << "\nLeading terminal for Production " << a[i][0] << " are: "; lead(a[i]); } return 0; } void lead(char s[]) { int i, j, k, t, m; t = strlen(s); for (i = 3; i < t; i++) { if ((!(s[i] >= char(65)) && (s[i] <= char(90)))) { cout << s[i] << ","; j = i; break; } else continue; } if (i == j) { for (j; j < t; j++) { if (s[j] == 47) { if ((s[j + 1]<char(65)) || (s[j + 1]>char(90))) cout << s[j + 1]; else { for (m = 0; m < n; m++) if (s[j + 1] == a[m][0]) { strcpy(temp, a[m]); lead(temp); } else {

continue; } } } } } } /** OUTPUT: Enter the no. of productions:3 E->F+T F->G*H T->F*K The production are: Production 1: E->F+T Production 2: F->G*H Production 3: T->F*K Leading terminal for Production E are: +, Leading terminal for Production F are: *, Leading terminal for Production T are: *, */

Experiment VI
Write a program to find Trailing terminals. Code: #include <iostream.h> #include <string.h> #include <ctype.h> char g[50][50], f[50][50]; int n,co; int search(char ch, int c) { int flag = 0; for (int i = 0; i < c; i++) if (f[i][0] == ch) { flag = 1; } if (flag == 1) return 0; else return 1; } void init() { int count1 = 0; for (int i = 0; i < n; i++) { if (search(g[i][0], count1)) { f[count1][0] = g[i][0]; f[count1][1] = char('0'); count1++; } } co = count1; } void place(char nterm, char term) { for (int i = 0; i < co; i++) { if (f[i][0] == nterm) { f[i][1]++; f[i][int(f[i][1]) - 48 + 1] = term; } } } void find_term(char a, char b) { int flag = 0; for (int i = 0; i < 6; i++) { if (int(g[i][0]) == int(a) && isupper(g[i][3]) && g[i][4] == '\0') { flag = 1; for (int k = 0; k < co; k++) { if (f[k][0] == g[i][3]) { for (int h = 2; h<int(f[k][1]) - 48 + 2; h++) { place(b, f[k][h]); }

find_term(g[i][3], b); } } } } if (flag == 0) return; } int main() { char g1[50][50]; cout << "Enter the number of productions: " ; cin >> n; cout << "Enter the grammer: " << endl; for (int i = 0; i < n; i++) { cin >> g1[i]; } for (int i = 0; i < n; i++) { g[i][0] = g1[i][0]; g[i][1] = g1[i][1]; g[i][2] = g1[i][2]; for (int j = 3, k = strlen(g1[i]) - 1; j <= k; j++, k--) { g[i][j] = g1[i][k]; } g[i][strlen(g[i])] = '\0'; } init(); for (int i = 0; i < n; i++) { for (int j = 3; g[i][j] != '\0'; j++) { if (!(isupper(g[i][j]))) { n++; place(g[i][0], g[i][j]); break; } } } for (int i = 0; i < co; i++) { find_term(f[i][0], f[i][0]); cout << endl; } cout << "The Trailing terminals for each non-terminal are: " << endl; for (int i = 0; i < co; i++) { for (int j = 0; j<int(f[i][1]) - 48 + 2; j++) { if (j == 1) continue; cout << f[i][j] << ": "; } cout << endl; } cout << endl; return 0; }

/** OUTPUT: Enter the number of productions: 3 Enter the grammer: E->A+B A->c*B B->d The Trailing terminals for each non-terminal are: E: + A: * B: d */

Experiment VII
Write a program for implementing Operator Precedence Parsing for given Grammar. Code: #include<stdio.h> int find(char a) { switch (a) { case 'a': return 0; case '+': return 1; case '*': return 2; case '$': return 3; } } void display(char a[], int top1, char b[], int top2) { int i; for (i = 0; i <= top1; i++) printf("%c", a[i]); printf("\t"); for (i = top2; i < strlen(b); i++) printf("%c", b[i]); printf("\n"); } int main() { char table[][4] = {' ', '>', '>', '>', '<', '<', '<', '>', '<', '>', '<', '>', '<', '<', '<', ' '}; char input[10]; char stack[10] = {'$'}; int top_stack = 0, top_input = 0; printf("Operator Precedence parsing for E->E+E/E*E/a\n"); printf("Enter the string : "); scanf("%s", input); strcat(input, "$"); printf("Stack\tInput\n"); display(stack, top_stack, input, top_input); while (1) { if ((stack[top_stack] == '$') && (input[top_input] == '$')) { printf("String accepted!!"); break; } if (table[find(stack[top_stack])][find(input[top_input])] == ' ') { printf("Parse error!!"); exit(0); } if (table[find(stack[top_stack])][find(input[top_input])] == '<') {

stack[++top_stack] = '<'; stack[++top_stack] = input[top_input]; top_input++; display(stack, top_stack, input, top_input); continue; } if (table[find(stack[top_stack])][find(input[top_input])] == '>') { stack[++top_stack] = '>'; display(stack, top_stack, input, top_input); top_stack -= 3; display(stack, top_stack, input, top_input); } } } /** OUTPUT: Operator Precedence parsing for E->E+E/E*E/a Enter the string : a*a+a Stack Input $ a*a+a$ $<a *a+a$ $<a> *a+a$ $ *a+a$ $<* a+a$ $<*<a +a$ $<*<a> +a$ $<* +a$ $<*> +a$ $ +a$ $<+ a$ $<+<a $ $<+<a> $ $<+ $ $<+> $ $ $ String accepted!! */

Experiment VIII
Write a program to perform the Shift Reduce Parsing. Code: #include<stdio.h> #include<string.h> void main() { char str[25], stk[25]; int i, j, t = 0, l; printf("Enter the String: "); scanf("%s", &str); l = strlen(str); str[l] = '$'; stk[t] = '$'; printf("\nStack\t\tString\t\tAction\n------------------------------------------\n "); for (i = 0; i < l; i++) { if (str[i] == 'i') { t++; stk[t] = str[i]; stk[t + 1] = str[i + 1]; for (j = 0; j <= t + 1; j++) printf("%c", stk[j]); printf("\t\t "); for (j = i + 2; j <= l; j++) printf("%c", str[j]); printf("\t\tShift"); printf("\n "); stk[t] = 'E'; i++; } else { t++; stk[t] = str[i]; } for (j = 0; j <= t; j++) printf("%c", stk[j]); printf("\t\t "); for (j = i + 1; j <= l; j++) printf("%c", str[j]); if (stk[t] == '+' || stk[t] == '*') printf("\t\tShift"); else printf("\t\tReduce"); printf("\n "); } while (t > 1) { if (stk[t] == 'E' && (stk[t - 1] == '+' || stk[t - 1] == '*') && stk[t - 2] == 'E') { t -= 2;

for (j = 0; j <= t; j++) printf("%c", stk[j]); printf("\t\t"); printf(" %c", str[l]); printf("\t\tReduce\n "); } else t -= 2; } if (t == 1 && stk[t] != '+' && stk[t] != '*') printf("\nThe Given String is Valid\n\n"); else printf("\nThe Given String is Invalid\n\n"); return 0; }

OUTPUT: Enter the String: a*a*a+a Stack String Action ------------------------------------------$a *a*a+a$ Reduce $a* a*a+a$ Shift $a*a *a+a$ Reduce $a*aA *a+a$ Reduce $a*aA *a+a$ Reduce $a*aa *a+a$ Reduce $a*aa *a+a$ Reduce $a*a* a+a$ Shift $a*a*a +a$ Reduce $a*a*a+ a$ Shift $a*a*a+a $ Reduce The Given String is Valid.

Experiment IX
Write a program to compute FIRST of a given grammar. Code: import java.util.HashMap; import java.util.Scanner; public class FirstFollow { static { System.out.println("Instructions for Input: "); System.out.println("1. All Non-Terminals should be represented by Capital Letters."); System.out.println("2. All Terminals should be represented by Small Letters or Symbols."); System.out.println("3. Enter EPSILON for \u0190"); System.out.println("4. No Terminal should be represented by more than one letter.\n"); } public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter the no. of productions: "); int size = s.nextInt(); System.out.println("Enter Productions: "); String[] input = new String[size]; for (int i = 0; i < size; i++) { System.out.print(i + 1 + ". "); input[i] = s.next(); } System.out.println(); First f = new First(input); //HashMap<String, String> first = f.displayFirst(); //new Follow(first).display(); } } import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; public class First { private private private private String input[]; ArrayList<String> nonTerminals; HashSet<String> terminals; HashMap<String, String> first;

public First() { this(new String[]{ "E->TE'",

"E'->+TE'|EPSILON", "T->FT'", "T'->*FT'|EPSILON", "F->(E)|d" }); } public First(String[] input) { this.input = input; terminals = new HashSet<>(); nonTerminals = new ArrayList<>(); first = new HashMap<>(); organizeLists(); } private void organizeLists() { String nterm[] = new String[input.length]; String term[] = new String[input.length]; for (int i = 0; i < input.length; i++) { String[] splitInput = input[i].split("->"); nterm[i] = splitInput[0]; term[i] = splitInput[1]; nonTerminals.add(nterm[i]); } for (int i = 0; i < term.length; i++) { term[i] = term[i].replaceAll("EPSILON", "\u0190"); for (String s : nonTerminals) { term[i] = term[i].replaceAll(s, ""); } term[i] = term[i].replaceAll("[|]", ""); for (char ch : term[i].toCharArray()) { terminals.add(String.valueOf(ch)); } } } private String getFirst(String nonTerminal) { int indexOf = nonTerminals.indexOf(nonTerminal); for (String s : terminals) { String[] split = input[indexOf].split("->"); String[] split1 = split[1].split("[|]"); for (String s1 : split1) { s1 = s1.replace("EPSILON", "\u0190"); if (s1.startsWith(s)) { if (first.containsKey(nonTerminal)) { if (!first.get(nonTerminal).contains(s)) { first.put(nonTerminal, first.get(nonTerminal) + s); } } else { first.put(nonTerminal, s);

} } } } for (String s : nonTerminals) { String[] split = input[indexOf].split("->"); if (split[1].startsWith(s)) { String first1 = getFirst(s); first.put(nonTerminal, first1); } } return first.get(nonTerminal); } public HashMap displayFirst() { for (String s : nonTerminals) { String first1 = getFirst(s); System.out.print("First(" + s + ")\t: { for (char ch : first1.toCharArray()) { System.out.print(ch + " "); } System.out.println(" }"); } return first; } } /** OUTPUT: Instructions for Input: 1.All Non-Terminals should be represented by Capital Letters. 2.All Terminals should be represented by Small Letters or Symbols. 3.Enter EPSILON for 4.No Terminal should be represented by more than one letter. Enter the no. of productions: 5 Enter Productions: 1. E->TE' 2. E'->+TE'|EPSILON 3. T->FT' 4. T'->*FT'|EPSILON 5. F->(E)|d First(E) First(E') First(T) First(T') First(F) */ : : : : : { { { { { d + d * d ( ( ( } } } } }

");

Experiment X
Write a program to compute FOLLOW of a given grammar. Code:
import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; public class Follow { private private private private private String input[]; ArrayList<String> nonTerminals; HashSet<String> terminals; HashMap<String, String> follow; HashMap<String, String> first;

public Follow(HashMap<String, String> first) { this(new String[]{ "E->TE'", "E'->+TE'|EPSILON", "T->FT'", "T'->*FT'|EPSILON", "F->(E)|d" }, first); } public Follow(String[] input, HashMap<String, String> first) { this.input = input; this.first = first; terminals = new HashSet<>(); nonTerminals = new ArrayList<>(); follow = new HashMap<>(); organizeLists(); } private void organizeLists() { String nterm[] = new String[input.length]; String term[] = new String[input.length]; for (int i = 0; i < input.length; i++) { String[] splitInput = input[i].split("->"); nterm[i] = splitInput[0]; term[i] = splitInput[1]; nonTerminals.add(nterm[i]); } for (int i = 0; i < term.length; i++) { term[i] = term[i].replaceAll("EPSILON", "\u0190"); for (String s : nonTerminals) { term[i] = term[i].replaceAll(s, ""); } term[i] = term[i].replaceAll("'", ""); term[i] = term[i].replaceAll("[|]", ""); for (char ch : term[i].toCharArray()) { terminals.add(String.valueOf(ch)); }

} } public String getFollow(String nonTerminal) { int index = nonTerminals.indexOf(nonTerminal); if (index == 0) { follow.put(nonTerminal, "$"); } for (String s : input) { String splitProductions[] = s.split("->"); String splitRHS[] = splitProductions[1].split("[|]"); for (String rhs : splitRHS) { if (rhs.equals("EPSILON")) { continue; } int len = rhs.length(); if (len != 0) { String last = rhs.charAt(len - 1) + ""; if (last.equals("'")) { last = rhs.charAt(len - 2) + "'"; } first: if (rhs.contains(nonTerminal) && !last.equals(nonTerminal)) { int indexOfNext = rhs.indexOf(nonTerminal) + 1; String next = rhs.charAt(indexOfNext) + ""; if (!terminals.contains(next) && rhs.contains("'")) { if (next.equals("'")) { break first; } else if (rhs.charAt(indexOfNext + 1) == '\'') { next += "'"; } } if (nonTerminals.contains(next)) { if (!follow.containsKey(nonTerminal)) { String f = first.get(next).replaceAll("\u0190", ""); follow.put(nonTerminal, f); } else { String newFollow = follow.get(nonTerminal); String firstOfNT = first.get(next); String firstOfLast = firstOfNT.replaceAll("\u0190", ""); for (char c : firstOfLast.toCharArray()) { if (!newFollow.contains(c + "")) { newFollow += c; } } if (firstOfNT.contains("\u0190")) { String followOfLHS; String lhsNT = splitProductions[0]; if (follow.containsKey(lhsNT)) { followOfLHS = follow.get(lhsNT); } else {

followOfLHS = getFollow(lhsNT); } for (char c : followOfLHS.toCharArray()) { if (!newFollow.contains(c + "")) { newFollow += c; } } } follow.put(nonTerminal, newFollow); } } else { if (follow.containsKey(nonTerminal)) { String f = follow.get(nonTerminal); if (!f.contains(next)) { f += next; follow.put(nonTerminal, f); } } else { follow.put(nonTerminal, next); } } } } } } String split[] = (input[index].split("->"))[1].split("[|]"); loop: for (String rhs : split) { if (rhs.equals("EPSILON")) { continue; } int pos = rhs.indexOf(nonTerminal); if (rhs.contains(nonTerminal) && rhs.contains("'")) { if (nonTerminal.contains("'")) { break loop; } else if (rhs.charAt(pos + 1) != '\'') { break loop;//rhs = rhs.replace(nonTerminal, ""); } } int len = rhs.length(); String last = "" + rhs.charAt(len - 1); if (last.equals("'")) { last = rhs.charAt(len - 2) + "'"; } if (nonTerminals.contains(last)) { if (follow.containsKey(nonTerminal)) { String lhsFollow = follow.get(nonTerminal); String rhsFollow; if (!follow.containsKey(last)) { rhsFollow = getFollow(last); } else { rhsFollow = follow.get(last); } String lhsNew = lhsFollow, rhsNew = rhsFollow; if (rhsFollow != null) { if (lhsFollow != null) {

for (char c : rhsFollow.toCharArray()) { if (!lhsFollow.contains("" + c)) { lhsNew += c; } } } else { lhsNew = rhsFollow; } } if (lhsFollow != null) { if (rhsFollow != null) { for (char c : lhsFollow.toCharArray()) { if (!rhsFollow.contains("" + c)) { rhsNew += c; } } } else { rhsNew = lhsFollow; } } follow.put(nonTerminal, lhsNew); follow.put(last, rhsNew); } else { if (!follow.containsKey(last)) { follow.put(nonTerminal, getFollow(last)); } else { follow.put(nonTerminal, follow.get(last)); } } } } return follow.get(nonTerminal); } public void display() { for (String s : nonTerminals) { String fol = getFollow(s); System.out.print("Follow(" + s + ")\t: { "); for (char ch : fol.toCharArray()) { System.out.print(ch + " "); } System.out.println("}"); } } }

OUTPUT: Follow(E) : { $ ) } Follow(E') : { $ ) } Follow(T) : { + $ ) } Follow(T') : { + $ ) } Follow(F) : { * + $ ) }

Experiment XI
Write a program to implement Top - Down Parsing using Arrays. Code: #include<stdio.h> #include<string.h> char *str; int a(int); int main() { int i; str = (char*) malloc(100); printf("\nEnter the string: "); gets(str); printf("\nThe length of string is: %d", strlen(str)); i = 0; if (str[i] == 'c') { i++; i = a(i); if (str[i] == 'd') printf("\nString Accepted"); else printf("\nString Not Accepted"); } else printf("\nString Not Accepted"); return 0; } int a(int i) { int p = i; if (str[i] == 'a') { i++; if (str[i] == 'b') { i++; return (i); } else { i = p; if (str[i] == 'a') i++; return (i); } } }

OUTPUT: Enter the string: cabbbad The length of string is: 7 String Not Accepted Enter the string: cabd The length of string is: 4 String Accepted

Experiment XII
Write a program to generate the intermediate code. Code: #include<stdio.h> #include<ctype.h> char s[20], t[20]; int main() { printf("Enter the expression: "); scanf("%s", &t); if (isalpha(t[2]) && isalpha(t[0]) && isalpha(t[4])) { printf("Mov %c,R \n", t[2]); } else printf("Enter correct exp: "); switch (t[3]) { case '*': printf("MUL %c,R \n", t[4]); printf("MOV R,%c \n", t[0]); break; case '+': printf("ADD %c,R \n", t[4]); printf("MOV R,%c \n", t[0]); break; case '-': printf("SUB %c,R \n", t[4]); printf("MOV R,%c \n", t[0]); break; case '/': printf("DIV %c,R \n", t[4]); printf("MOV R,%c \n", t[0]); break; default: printf("INVALID OPERATOR!!"); break; } return 0; }

OUTPUT: Enter the expression: a=b+c Mov b,R ADD c,R MOV R,a

Experiment XIII
WAP to validate an input string against the given Grammar. Code: import java.util.Scanner; public class Grammer { String grammer; String input; boolean valid; public Grammer() { valid= false; } private static String inputLine() { Scanner s = new Scanner(System.in); return s.nextLine(); } public static void main(String[] args) { Grammer g = new Grammer(); System.out.println("Input EPSILON for \u0190"); System.out.print("Grammer : "); String inputGrammer = inputLine(); while(true) { System.out.print("\nInput String : "); String inputText = inputLine(); if(inputText.equalsIgnoreCase("exit")) break; g.validateText(inputGrammer, inputText); } } private void validateText(String grammer, String input) { valid = false; String[] split = grammer.split("->",2); String[] inputTokens = split[1].split("[|]"); String minimalString = grammer; for(String s: inputTokens) if((!s.contains("S") && minimalString.length()>=s.length()) || s.equalsIgnoreCase("EPSILON")) if(s.equalsIgnoreCase("EPSILON")) minimalString = ""; else minimalString = s; String temp = ""; for(String s:inputTokens) if(s.startsWith(String.valueOf(input.charAt(0))) && !s.equals(minimalString)) temp = s; while (temp.length() + minimalString.length()<=input.length() + 1 && !temp.equals("")) { if(temp.contains("S")){

if(temp.equals(input) || minimalString.equals(input) || temp.replace("S", minimalString).equals(input)){ valid = true; break; } } else { if(temp.equals(input)) valid = true; break; } int index; char ch = 'S'; if((index = temp.indexOf("S"))!=-1) ch = input.charAt(index); for(String s:inputTokens) if(s.startsWith(String.valueOf(ch)) && !s.equals(minimalString)){ temp = temp.replace("S", s); break; } else if(s.equals(minimalString) || s.equalsIgnoreCase("epsilon")) temp = temp.replace("S", minimalString); } if(valid) System.out.println("Input string is Valid for the given Grammer!!"); else System.out.println("Input string is Invalid for the given Grammer!!"); } } OUTPUT: Input EPSILON for Grammer : S->aSb|ab Input String : aabbb Input string is Invalid for the given Grammer!! Input String : ababab Input string is Invalid for the given Grammer!! Input String : aabb Input string is Valid for the given Grammer!! Input String : aaabbb Input string is Valid for the given Grammer!!

Vous aimerez peut-être aussi