LEX program to print the longest string and to find average of given numbers
The Lex program has purpose of generating lexical analyzer. Lex analyzers are a program that transform input streams into sequence of tokens. A C program implements the lexical analyzer to read input stream and produce output as the source code.
Commands to be used –
lex file_name.l // To produce a c program cc lex.yy.c -lfl // To compile the c program and produces object program a.out. ./a.out // To transforms an input stream into a sequence of tokens.
1. Longest string :
In this we are finding the length of longest string by using the function called ( It returns the length of a given string). And we are storing this returned value in the variable . To print what string or word is longest we are using and function. We are storing the string or word in a variable of type char that is .
2. Average of given numbers :
So, first we have to calculate sum of all numbers that are given by user. Store sum in a variable sum. Then count number of integers(numbers that are given by the user). Store this count in a variable n.
After this, just divide the sum and count of numbers. You will get your result.
Here, we are using inbuild function atoi(). A string of characters can be passed into atoi() function, which will convert them into an integer. The input string is a text string that can be converted into a numeric value. When first character in input string is not part of a number, atoi() function stops reading it. This could be null character at the end of string. It does not support exponents and decimals.
The atoi() function removes all the Whitespace in string at beginning.