0% found this document useful (0 votes)
9 views2 pages

Assignment1 Compiler Lab

Uploaded by

Filza Zarqa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views2 pages

Assignment1 Compiler Lab

Uploaded by

Filza Zarqa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PROGRAM 1

Write a program in C to create a DFA that accepts all strings starting with
'a', with the alphabet consisting of 'a' and 'b'.
DFA:

Transition table:
State a b
q0 q1 q2
q1 q1 q1
q2 q2 q2

Code:
#include <stdio.h>
#include <string.h>
#define TRAP_STATE -1
int transition_table[3][2] = {
{1, 2},
{1, 1},
{2, 2}
};
int get_next_state(int current_state, char input)
{
int column = (input == 'a') ? 0 : (input == 'b') ? 1 : TRAP_STATE;
if (column == TRAP_STATE)
return TRAP_STATE;
return transition_table[current_state][column];
}

Zarqa Gulrez(22310237)
int is_accepted(char *string)
{
int current_state = 0;
for (int i = 0; i < strlen(string); i++)
{
current_state = get_next_state(current_state, string[i]);
if (current_state == TRAP_STATE) return 0;
}
return current_state == 1;
}
int main()
{
char input[100];
printf("Enter a string with alphabets 'a' and 'b': ");
scanf("%s", input);
if (is_accepted(input))
{
printf("The string is accepted by the DFA.\n");
}
else
{
printf("The string is rejected by the DFA.\n");
}
return 0;
}
Output:

Zarqa Gulrez(22310237)

You might also like