Lex program to check whether an year is a leap year or not

Problem: Write a Lex program to check whether an year is a leap year or not.

Explanation:
Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.

Note: Leap years are the years that are divisible by 400 or are divisible by 4 and not divisible by 100. So 2016, 2020 etc are leap years while 2017 and 2019 are not.

Examples:

Input: 2016 
Output: leap year

Input: 2017
Output: not a leap year 

Implementation:

filter_none

edit
close

play_arrow

link
brightness_4
code

/*Lex program to check whether an year is a leap year or not*/
  
%{
 void check(char *);
%}
  
/*Rule Section*/
 %%   
[0-9]    ;
[0-9][0-9]    ;
[0-9][0-9][0-9]     ;
[0-9][0-9][0-9][0-9]    { printf("%s", yytext);check(yytext); }
[0-9][0-9][0-9][0-9][0-9]+ ;
 %%
  
// driver program
int main()
{
    extern FILE *yyin;
    yyin=fopen("num", "r");
  
    // The function that starts the analysis 
    yylex();
    return 0;
  
}
  
void check(char *a)
{
    int x=0, i;
  
    for(i=0;i<4;i++)
        x=x*10+(a[i]-'0');
  
    if(x%400==0)   
        printf("\tleap year\n");
  
    else if(x%4==0&&x%100!=0)
        printf("\tleap year\n");
  
    else
        printf("\tnot a leap year\n");
}

chevron_right


Output:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.