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

Lab 5

This C program validates C identifiers by checking strings against a list of keywords and transition states. It gets a string from the user, checks if it is a keyword, and then uses a delta transition function with states to determine if the rest of the string is a valid identifier. If the final state is the accept state, it prints that the string is valid, otherwise it is not a valid identifier or keyword.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views

Lab 5

This C program validates C identifiers by checking strings against a list of keywords and transition states. It gets a string from the user, checks if it is a keyword, and then uses a delta transition function with states to determine if the rest of the string is a valid identifier. If the final state is the accept state, it prints that the string is valid, otherwise it is not a valid identifier or keyword.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Lab-5:

Write a program to validate C identifiers.

Source code:

#include <stdio.h>
#include <string.h>
char keyword[32][10] = {"auto", "double", "int", "struct", "break", "else", "long",
"switch", "case", "enum", "register", "typedef", "char", "extern", "return", "union",
"const", "float", "short", "unsigned", "continue", "for", "signed", "void", "default",
"goto", "sizeof", "volatile", "do", "if", "static", "while"};
enum states
{
q0,
qf,
qd
};
enum states delta(enum states, char);
int iskeyword(char[]);
int Data;
int main()
{
enum states curr_state = q0;
char string[20], ch;
int i = 0;

printf("\n Enter a string: \n");


gets(string);
ch = string[i];
if (iskeyword(string))
printf("\n The string %s is keyword.", string);
else
{
while (ch != '\0')
{
curr_state = delta(curr_state, ch);
ch = string[++i];
}
if (curr_state == qf)
printf("\n The string %s is valid indentifier.", string);
else
printf("\n The string %s is neither keyword nor valid identifier.", string);
}
return 0;
} // end of the main

// transition function
enum states delta(enum states s, char ch)
{
enum states curr_state;
switch (s)
{
case q0:
if (ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z' || ch == '_')
curr_state = qf;
else
curr_state = qd;
break;
case qf:
if (ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z' || ch == '_' || ch >= '0' && ch <= '9')
curr_state = qf;
else
curr_state = qd;
break;
case qd:
curr_state = qd;
}

return curr_state;
}
int iskeyword(char str[])
{
for (int i = 0; i < 32; i++)
{
if (strcmp(str, keyword[i]) == 0)
return 1;
}
return 0;
}
Output:

You might also like