Tuesday 1 April 2014

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

Leap years are the years that are divisible by 400 or are divisible by 4 and not divisible by 100.
So 2000,2012 etc are leap years while 1900, 2001 etc are not

Here is the code:

%{
void check(char *);
%}
%%   
[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]+ ;
%%
main()
{
    extern FILE *yyin;
    yyin=fopen("num","r");
    yylex();
}
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("\tYES\n");
    else if(x%4==0&&x%100!=0)
        printf("\tYES\n");
    else
        printf("\tNO\n");
}

No comments:

Post a Comment