4B) Program to recognize a valid variable, which starts with a letter, followed by any number of letters or digits. [VTU SS&OS]

vtu ss & os 4b
Code:
LEXX:
YACC:

Explanation:
This program checks whether a variable is valid or not.

Lex:
%{ 
#include "y.tab.h" 
%}

Declaration section. Include y.tab.h for making lexer read the input symbol so that it can send tokens to Yacc parser.

%% 
[a-zA-z_]    {return ALPHA;} 
[0-9]+         {return NUMBER;} 
"\n"             { return ENTER;} 
.                  {return ER;} 
%%
yywrap()
{}

return proper tokens in this lexer part.

  • if character is encountered, return ALPHA token to parser.
  • similarly, if number is encoutered, return NUMBER token, if newline character, then return ENTER token, and if any other character, return ER token.
yywrap() function is responsible for checking whether there are any more inputs. If no, then yywrap() tells program to end.


Yacc:
%{
#include <stdio.h>
#include<stdlib.h>
%} 
%token ALPHA    NUMBER    ENTER    ER 

define header files and tokens which are returned from lexer.

%% 
var:v ENTER  {printf("Valid Variable\n");exit(0);} 
v:ALPHA exp1 
exp1:ALPHA exp1 
|NUMBER exp1 
| ; 
%% 

Its a grammar.

  • var is the grammar which defines, if v is followed by ENTER token, and if v is valid, we print "Valid" and then exit.
  • v is defined as an alphabet, folllowed by and exp1.(variable should start with alphabet or underscore only. and ALPHA token represents those two as you can see in lexer).
  • exp1 is defined multiple ways. as you can see above.(a character/number followed by exp1. Or nothing.)
  • This way, input is rcursively checked against grammar. If its successfully matched, v is valid. and we display "Valid" message.


yyerror() 

printf("Invalid Variable\n"); 

main() 

printf("Enter the expression:"); 
yyparse(); 

}

yyerror() is called when v was not valid in the previous snippet.
main() function scans for the variable. Note that "Valid" was displayed in the previous snippet if v was valid.

He is a simple passionate tech freak who himself is an engineering student at Canara Engineering college. He likes App Development, Web designing, Blogging, Youtubing, Debugging and also is a CodeGeek!

Sharing is sexy!

Related Articles

3 comments

Write comments
Anonymous
AUTHOR
1 December 2016 at 10:24 delete

Please add the explanations as soon as possible ... These are very helpful and I have lab on 5th Dec :). Thank you so much for all these btw.

Reply
avatar
Unknown
AUTHOR
3 December 2016 at 21:24 delete

Thanks for the review :)
All explanations are published now. Hope you like it!
-CodeShuffle

Reply
avatar
Anonymous
AUTHOR
4 December 2016 at 21:25 delete

Thanks a lot! really helpful!

Reply
avatar

Share your views about this article!