0% found this document useful (0 votes)
1 views

Compiler Design Lab Experiment 2

The document outlines an experiment for implementing a Deterministic Finite Automaton (DFA) that simulates the regular expression a + (aa)*b. It includes C code that defines the DFA states, simulates transitions based on input, and checks if the input string is accepted or rejected. The program prompts the user for a string consisting of 'a' and 'b' and outputs the acceptance result.

Uploaded by

nazmasultana2004
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Compiler Design Lab Experiment 2

The document outlines an experiment for implementing a Deterministic Finite Automaton (DFA) that simulates the regular expression a + (aa)*b. It includes C code that defines the DFA states, simulates transitions based on input, and checks if the input string is accepted or rejected. The program prompts the user for a string consisting of 'a' and 'b' and outputs the acceptance result.

Uploaded by

nazmasultana2004
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Compiler Design Lab

COURSE CODE: 18B17CI672

Experiment 2
Implement a DFA which simulates the regular expression a + (aa)*b.

Code:-
#include <stdio.h>
#include <string.h>

// DFA states
typedef enum {
Q0, // Start state
Q1, // After reading 'a'
Q2, // After reading "aa"
Q3 // Accepting state after "b"
} State;

// Function to simulate the DFA


int simulate_dfa(const char *input) {
State current_state = Q0; // Start at state q0

for (int i = 0; input[i] != '\0'; i++) {


char c = input[i];
switch (current_state) {
case Q0:
if (c == 'a') {
current_state = Q1;
} else {
return 0; // Invalid transition
}
break;

case Q1:
if (c == 'a') {
current_state = Q2;
} else if (c == 'b') {
current_state = Q3;
} else {
return 0; // Invalid transition
}
break;

Nazma Sultana (221030402)


case Q2:
if (c == 'a') {
current_state = Q2;
} else if (c == 'b') {
current_state = Q3;
} else {
return 0; // Invalid transition
}
break;

case Q3:
return 0; // No transitions allowed from Q3
}
}

// Check if the current state is accepting


return (current_state == Q1 || current_state == Q3);
}

int main() {
char input[100];

printf("Enter a string (only 'a' and 'b' allowed): ");


scanf("%s", input);

// Check if the input string is accepted by the DFA


if (simulate_dfa(input)) {
printf("The string '%s' is accepted by the DFA.\n", input);
} else {
printf("The string '%s' is rejected by the DFA.\n", input);
}

return 0;
}

Nazma Sultana (221030402)


Nazma Sultana (221030402)

You might also like