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.

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.


Input: 2016 
Output: leap year

Input: 2017
Output: not a leap year 






/*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 
    return 0;
void check(char *a)
    int x=0, i;
        printf("\tleap year\n");
    else if(x%4==0&&x%100!=0)
        printf("\tleap year\n");
        printf("\tnot a leap year\n");



Attention reader! Don’t stop learning now. Get hold of all the important CS Theory concepts for SDE interviews with the CS Theory Course at a student-friendly price and become industry ready.

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 :


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