Open in App
Not now

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

• Last Updated : 01 May, 2019

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:

 `/*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"``); ` `} `

Output:

My Personal Notes arrow_drop_up
Related Articles