Program to build DFA that starts and ends with 'a' from the input (a, b)

DFA stands for Deterministic Finite Automata. It is a finite state machine that accepts or rejects a string based on its transition rules and final states.

Here, we are going to make a DFA that accepts a string that starts and ends with 'a'. The input alphabet is from the set {a, b}. Let's discuss some valid and invalid cases that are accepted by this DFA.

Strings accepted by DFA: "ababba", "aabba", "aa", "a"

Strings not accepted by DFA: "ab", "b", "aabab"

Syntax

// Check if string starts and ends with 'a'
if (str[0] == 'a' && str[length-1] == 'a') {
    // String accepted
}

DFA State Diagram

q0 (Start) q1 (Accept) q2 (Dead) a b a b a b Start

Example: DFA Implementation

This program implements a DFA to check if a string starts and ends with 'a' −

#include <stdio.h>
#include <string.h>

int checkDFA(char str[]) {
    int length = strlen(str);
    
    // Empty string is rejected
    if (length == 0) {
        return 0;
    }
    
    // Single character must be 'a'
    if (length == 1) {
        return (str[0] == 'a');
    }
    
    // Check if starts and ends with 'a'
    if (str[0] == 'a' && str[length-1] == 'a') {
        return 1; // Accepted
    }
    
    return 0; // Rejected
}

int main() {
    char test1[] = "ababba";
    char test2[] = "aabba";
    char test3[] = "ab";
    char test4[] = "a";
    
    printf("String '%s': %s<br>", test1, checkDFA(test1) ? "Accepted" : "Rejected");
    printf("String '%s': %s<br>", test2, checkDFA(test2) ? "Accepted" : "Rejected");
    printf("String '%s': %s<br>", test3, checkDFA(test3) ? "Accepted" : "Rejected");
    printf("String '%s': %s<br>", test4, checkDFA(test4) ? "Accepted" : "Rejected");
    
    return 0;
}
String 'ababba': Accepted
String 'aabba': Accepted
String 'ab': Rejected
String 'a': Accepted

DFA State Transition Table

State Input 'a' Input 'b' Final State
q0 (Start) q1 q2 No
q1 (Accept) q1 q2 Yes
q2 (Dead) q1 q2 No

How It Works

  • State q0: Initial state. On reading 'a', move to accepting state q1. On reading 'b', move to dead state q2.
  • State q1: Accepting state (string ends with 'a'). Stay in q1 on 'a', move to q2 on 'b'.
  • State q2: Dead state (last character was 'b'). Move to q1 on 'a', stay in q2 on 'b'.

Conclusion

This DFA efficiently recognizes strings that start and end with 'a' using three states. The implementation checks the first and last characters, ensuring the string meets the acceptance criteria for the given alphabet {a, b}.

Updated on: 2026-03-15T11:19:57+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements