I have been writing a code that either accepts or rejects a string of input symbols as part of a specified language. And I have written code for the first language but it doesn’t accept the right thing and i was wondering if any one could give me a hint as to where i went wrong. thanks
Question: Why wont the language be accepted or rejected correctly?
Thanks
My code:
#include <stdio.h>
static final char initial_state = '0';
static final char 0 = '0';
static final char 1 = '1';
static final char 2 = '2';
static final char 3 = '3';
int main(int argc, char* argv[]){
int x;
char current_state, next_state, initial_state;
current_state = initial_state;
printf("Enter a string of characters: ");
while(scanf("%d", &x)!=EOF){
switch(current_state){
case 0: /*initial state*/
switch(current_state){
case'0':next_state=1; break;
case'1':next_state=0; break;
}
break;
case 1: /*Last input was 0*/
switch(current_state){
case'0':next_state=1; break;
case'1':next_state=2; break;
}
break;
case 2: /*Last input was 1*/
switch(current_state){
case'0':next_state=3; break;
case'1':next_state=0; break;
}
break;
case 3: /*Last input was 0*/
switch(current_state){
case'0':next_state=3; break;
case'1':next_state=3; break;
}
break;
}
current_state=next_state;
}
if((current_state==next_state)){
printf("Language 1 accepts");
}else if((current_state!=next_state)){
printf("Language 1 rejects");
}
return 0;
}
You have defined
initial_statetwice, and the local one is winning the “scope war.” So in your code, every time you think you’re referring to thisinitial_state:you’re actually referring to this initial state:
Additionally, you’re doing some numerics and some characters. You want all characters since you’re taking input from the keyboard. Any place that you define a state as a 1 or a 0, put single quotes around it so it’s a
'1'or a'0'.Then, take out the code that redefines
1 = '1'for all the states; I do believe you’re asking the program to redefine the number 0x1 to mean the number 0x41 — that’s crazy.Here’s the final result (badly formatted):