Untitled
unknown
plain_text
a year ago
1.5 kB
11
Indexable
#include <stdio.h>
// Define the states of the FSM
typedef enum { Q0, Q1, REJECT } State;
// Transition function for the FSM
State transition(State currentState, char input) {
switch (currentState) {
case Q0:
if (input == 'a') {
return Q1; // Transition from Q0 to Q1 on 'a'
} else {
return REJECT; // Transition to REJECT on any other input
}
case Q1:
return Q1; // Stay in Q1 for any input after 'a'
default:
return REJECT; // Stay in REJECT state for any input
}
}
// Function to check if the string starts with 'a'
int startsWithA(const char *str) {
State currentState = Q0; // Start at the initial state (Q0)
int i = 0;
// Process each character in the input string
while (str[i] != '\0') {
currentState = transition(currentState, str[i]); // Get the next state
if (currentState == REJECT) {
return 0; // If in REJECT state, return false (0)
}
i++;
}
// Return 1 (true) if the final state is Q1, otherwise return 0 (false)
return (currentState == Q1);
}
int main() {
char input[100];
// Prompt the user to enter a string
printf("Enter a string: ");
scanf("%s", input);
// Check if the string starts with 'a'
if (startsWithA(input)) {
printf("The string starts with 'a'.\n");
} else {
printf("The string does not start with 'a'.\n");
}
return 0;
}
Editor is loading...
Leave a Comment