Compiler Assesment 1
Compiler Assesment 1
Task: ASSESSMENT-1
____________________
Dr. Sureshkumar WI
Aim:
• To implement a DFA from a given regular grammar using the C programming language.
• To implement a DFA using LEX code that accepts strings with an odd number of 0's
and an even number of 1's.
• To implement a DFA using LEX code that accepts strings over the alphabet {0, 1}
ending with "11".
Algorithm:
a)
2. Initialize the DFA with the start state and accepting states.
5. Check if the final state after processing the input string is an accepting state.
b)
1. Define the states and transitions for odd 0's and even 1's and another for ending with
two 1’s.
3. Track the count of 0's and 1's and transition between states accordingly.
4. Accept the string if it ends in the state corresponding to odd 0's and even 1's and for
the other case ending with two 1’s .
Source Code:
a)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_ALPHABET 26
#define MAX_STATE_NAME_LENGTH 10
typedef struct {
int numStates;
int numFinalStates;
char states[MAX_STATES][MAX_STATE_NAME_LENGTH];
char finalStates[MAX_STATES][MAX_STATE_NAME_LENGTH];
int transition[MAX_STATES][MAX_ALPHABET];
char startState[MAX_STATE_NAME_LENGTH];
char alphabet[MAX_ALPHABET];
} DFA;
dfa->numStates = 0;
dfa->numFinalStates = 0;
if (dfa->alphabet[i] == symbol) {
return i;
}
return -1;
if (strcmp(dfa->states[i], state) == 0) {
return i;
return -1;
scanf("%d", &dfa->numStates);
scanf("%s", dfa->states[i]);
scanf("%s", dfa->alphabet);
printf("Enter number of final states: ");
scanf("%d", &dfa->numFinalStates);
scanf("%s", dfa->finalStates[i]);
scanf("%s", dfa->startState);
scanf("%s", toState);
dfa->transition[i][j] = toStateIndex;
printf("\nTransition Table:\n");
printf("State\\Symbol\t");
for (int i = 0; i < strlen(dfa->alphabet); i++) {
printf("%c\t", dfa->alphabet[i]);
printf("\n");
printf("%s\t\t", dfa->states[i]);
if (dfa->transition[i][j] != -1) {
printf("%s\t", dfa->states[dfa->transition[i][j]]);
} else {
printf("NULL\t");
printf("\n");
printf("\n");
if (alphabetIndex == -1) {
return 0;
}
currentStateIndex = dfa->transition[currentStateIndex][alphabetIndex];
if (currentStateIndex == -1) {
return 0;
if (strcmp(dfa->states[currentStateIndex], dfa->finalStates[i]) == 0) {
return 1;
return 0;
int main() {
DFA dfa;
initializeDFA(&dfa);
inputDFA(&dfa);
printTransitionTable(&dfa);
char inputString[100];
while(1) {
scanf("%s", inputString);
if(strcmp(inputString, "end") == 0) {
return 0;
if (isAccepted(&dfa, inputString)) {
} else {
return 0;
b) i)
%{
%}
%s Q1 Q2 Q3 DEAD
%%
%%
int main()
printf("Enter String\n");
yylex();
return 0;
b) ii)
%{
%}
%s Q1 Q2 DEAD
%%
%%
int main()
printf("Enter String\n");
yylex();
return 0;
b) i)
b) ii)
Conclusion:
• Successfully implemented a DFA in LEX that accepts strings with an odd number of
0's and an even number of 1's.
• Successfully implemented a DFA in LEX that accepts strings over {0, 1} ending with
"11".