Count The Positive numbers, Negative numbers & Fractions - Lex Program - Compiler Design

Aim:
Write a lex program to count the number of Positive numbers, Negative numbers & Fractions.

Program:

// lex file: a.l

%{
    int postiveno=0;
    int negtiveno=0;
    int positivefractions=0;
    int negativefractions=0;
%}

DIGIT [0-9]
%%

\+?{DIGIT}+                              postiveno++;
-{DIGIT}+                                  negtiveno++;

\+?{DIGIT}*\.{DIGIT}+            positivefractions++;
-{DIGIT}*\.{DIGIT}+                negativefractions++;
. ;   
%%

main()
{
    yylex();
    printf("\nNo. of positive numbers: %d",postiveno);
    printf("\nNo. of Negative numbers: %d",negtiveno);
    printf("\nNo. of Positive fractions: %d",positivefractions);
    printf("\nNo. of Negative fractions: %d\n",negativefractions);
}

Output:

nn@linuxmint ~ $ lex a.l
nn@linuxmint ~ $ gcc lex.yy.c -ll
nn@linuxmint ~ $ ./a.out<a.txt


No. of positive numbers: 2
No. of Negative numbers: 3
No. of Positive fractions: 4
No. of Negative fractions: 5
nn@linuxmint ~ $

// Input file: a.txt
+12,-123,1.1,-1.1,12,-2,-3,2.1,3.2,5.1,-5.5,-6.1,-7.7,-8.8

5 comments:

  1. i required linux lex program for -ve to +ve no. conversion

    ReplyDelete
  2. i required a solution for that if two negatives are given to a number,then how can it be count?

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. For what mean .; stands for
    -{DIGIT}*\.{DIGIT}+ negativefractions++;
    above line ?

    ReplyDelete
  5. What about -9..90

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...