CS 370 Lab 3: Finite Automata and Context Free Grammars

This lab is due at start of class February 23.

Name: ____________________________________________________

Part A: Finite Automata

1. Draw Nondeterministic Finite Automata Equivalent to the Regular Expressions:

[ab]*a(a|b|ε)





(a|b)+d





(a|b)*a(a|b)(a|b)





2. Draw Deterministic Finite Automata Equivalent to the Regular Expressions:

[ab]*a(a|b|ε)





(a|b)+d





(a|b)*a(a|b)(a|b)





Part B: Context Free Grammars

1. Study the following grammar. This CFG notation uses colon ( : ) to separate the lefthandside nonterminal from its production rule, the "OR" bar ( | ) to end the current production and start a new production rule for the same nonterminal, and the semicolon ( ; ) to terminate a production.
list		: expr
		| list COMMA expr
		;
expr		: CONST
		| IDENT
		| expr PLUS expr
		| expr MINUS expr
		;
What are the terminal symbols:

What are the non-terminal symbols:

How many production rules are in this grammar:


2. Remove left-recursion from the grammar given in problem #1. Note that expr has two left-recursive productions and requires special care.




3. Write a context free grammar for palindromes in the alphabet {a,b,c}. A palindrome is a string that is equal to its reverse, such as "abba", or "acaca".

4. Let G be the grammar

S -> aB | bA
A -> a | aS | bAA
B -> b | bS | aBB
For the string aaabbabbba, find a right-most derivation, and draw its parse tree.

5. Consider the grammar

S -> AA
A -> AAA | a | bA | Ab
List the strings of terminals that can be derived by four or fewer steps.

6. Consider the alphabet {a, b, (, ), |, *, ε}. Using this alphabet, construct a context free grammar for regular expressions over {a, b}.

7. Eliminate the left recursion from the following grammar fragment.

S -> TypeDeclarationsOpt
TypeDeclarationsOpt-> TypeDeclarations | ε
TypeDeclarations-> TypeDeclaration | TypeDeclarations TypeDeclaration
TypeDeclaration-> basetype ident semicolon

Part 3: Hand Simulation

3. Draw Memory Box Pictures and then Hand Simulate the Following Code

 int f(int y) {
 int x;
 char *c, s[10];
 x = 5;
 c = s;
 c[10] = '\0';
 c = "Hello";
}

4. Draw Memory Box Pictures and then Hand Simulate the Following Code

struct tlist { struct tok *t; struct tlist *next; } ;
/* append a COPY of t to the end of l */
int append(struct tok *t, struct tlist *l)
{
   struct tlist *lp;
   struct tok *p;
   if (l == NULL) return -1;
   if (lp = malloc(sizeof(struct tlist)) == NULL)
      return -2;
   lp->next = NULL;
   if ((lp->t = malloc(sizeof(struct tok))) == NULL) {
      free(lp);
      return -3;
      }
   *(lp->t) = *t;

   while(l->next != NULL) l = l->next;
   l->next = lp;
   return 0;
}