Ram Lal Anand College
University of Delhi
              Department of Computer Science
                      Session : 2023 – 2024
                Final Practical File
Course Name – B.Sc. (Hons) Computer Science
Semester – 5th
Title of the Paper – System Programming
Paper Code - 32347501
Name of the Student –
Examination Roll No –
Ques-1 Write a Lex program to count the number of lines and
characters in the input file.
Solution-
%option noyywrap
%{
int lines=0;
int characters=0;
%}
%%
. characters++;
\n {lines++;characters++;}
%%
int main()
{
     yyin = fopen("input.txt","r");
     yylex();
     printf("number of lines: %d\n",lines+1);
     printf("number of characters: %d\n",characters+1);
     return 0;
# input.txt
Output-
Ques-2 Write a Lex program that implements the Caesar cipher: it
replaces every letter with the one
three letters after in alphabetical order, wrapping around at Z. e.g. a is
replaced by d, b by e,
and so on z by c.
Solution -
%{
 int rot = 0;
%}
%%
[A-Z] { fprintf(yyout, "%c", (yytext[0] - 'A' + rot) % 26 + 'A'); }
[a-z] { fprintf(yyout, "%c", (yytext[0] - 'a' + rot) % 26 + 'a'); }
. { fprintf(yyout, "%s", yytext); }
%%
int main(void) {
  printf("Enter Key (ROT): ");
  scanf("%d", &rot);
  yyin = fopen("input.txt", "r");
  yyout = fopen("output.txt", "w");
  yylex();
  fclose(yyin);
  fclose(yyout);
  printf("Successfully changed the value!");
  return 0;
}
int yywrap() {
  return 1;
}
Input file-
Output-
Output file -
Ques-3 Write a Lex program that finds the longest word (defined as a
contiguous string of upper-
and lower-case letters) in the input.
Solution -
%option noyywrap
%{
       #include<string.h>
       int longest = 0;
       char word[1000];
%}
%%
[a-zA-Z0-9]+ {
     if(yyleng>longest){
           longest = yyleng;
           strcpy(word,yytext);
     }
}
[ |\n|\r|\t] { ; }
.{;}
%%
int main(void){
     yyin = fopen("text.txt", "r");
     yylex();
     fclose(yyin);
     printf("The longest string is %s \n", word);
     printf("Length of a longest string is %d \n",longest);
}
Ques-4 Write a Lex program that distinguishes keywords, integers,
floats, identifiers, operators, and
comments in any simple programming language.
Solution-
%{
  int integers = 0;
  int floats = 0;
  int identifiers = 0;
  int operators = 0;
  int comments = 0;
%}
%%
[#].* { printf("%s <- preprocessor directive\n", yytext); } // preprocessor
directives
[ |\n|\t] { ; } // whitespaces
[,|;|"("|")"|"{"|"}"|"\["|"\]"] { ; } // brackets, delimiters
"//".* { comments++; printf("%s <- comment\n", yytext); } // single line
comments
[0-9]+ { integers++; printf("%s <- integer\n", yytext); } // integers
[0-9]+("."[0-9]+) { floats++; printf("%s <- float\n", yytext); } // floats
void|int|main|char|for|while|continue|switch|case|break|if|else|
return|true|false { printf("%s <- keyword\n", yytext); } // keywords
"<="|">="|"!
="|"=="|"<"|">"|"&"|"|"|"^"|"<<"|">>"|"~"|"&&"|"||"|"!"|"+
+"|"--"|"="|"+"|"-"|"*"|"/"|"%" { operators++; printf("%s <- operator\
n", yytext); } // operators
[']([^\\\']|\\.)?['] { ; } // characters
["]([^\\\"]|\\.)*["] { ; } // strings
[a-zA-Z_]+[a-zA-Z0-9_]* { identifiers++; printf("%s <- identifier\n",
yytext); } // identifiers
%%
int main() {
  yyin = fopen("t1.c", "r");
  yylex();
  printf("\n");
  printf("number of integers: %d\n", integers);
  printf("number of floats: %d\n", floats);
  printf("number of identifiers: %d\n", identifiers);
  printf("number of operators: %d\n", operators);
  printf("number of comments: %d", comments);
  return 0;
}
int yywrap() {
  return 1;
}
Input File-
Output-
Ques-5 Write a Lex program to count the number of identifiers in a C
file.
Solution-
%option noyywrap
%{
   int identifiers = 0;
%}
%%
[#].* { ; } // preprocessor directives
[ |\n|\t] { ; } // whitespaces
[,|;|"("|")"|"{"|"}"|"\["|"\]"] { ; } // brackets, delimiters
"//".* { ; } // single line comment
-?[0-9]+("."[0-9]+)? { ; } // numbers
void|int|main|char|for|while|continue|switch|case|break|if|else|return|
true|false { ; } // keywords
"<="|">="|"!="|"=="|"<"|">" { ; } // relational operators
"&"|"|"|"^"|"<<"|">>"|"~" { ; } // bitwise operators
"&&"|"||"|"!" { ; } // logical operators
"++"|"--" { ; } // postfix/prefix operators
"="|"+"|"-"|"*"|"/"|"%" { ; } // other operators
[']([^\\\']|\\.)?['] { ; } // characters
["]([^\\\"]|\\.)*["] { ; } // strings
[a-zA-Z_]+[a-zA-Z0-9_]* { identifiers++; printf("%s <- identifier\n", yytext); } //
identifiers
%%
int main() {
  yyin = fopen("text.c", "r");
  yylex();
  printf("\nnumber of C identifiers: %d\n", identifiers);
  return 0;
}
Input file-
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// This is my code
void loop()
{
  int i, j = 7;
  for (int i = 0; i < j; i++)
  {
    printf("%d. Hello\n", (j + 1));
  }
}
int main()
{
  double a = -3.14;
  char at = '@', tab = '\t';
    loop();
    return 0;
}
Output-
Ques-6 Write a Lex program to count the number of words, characters, blank
spaces and lines in a C
file.
Solution-
%{
  int words = 0;
  int lines = 0;
  int spaces = 0;
  int characters = 0;
%}
%%
[^ \t\n,\.:;]+ { words++; characters += yyleng; }
[\n] { lines++; characters += yyleng; }
[ |\t] { spaces++; characters += yyleng; }
. { characters++; }
%%
int main() {
  yyin = fopen("text.c", "r");
  yylex();
  printf("number of words: %d\n", words);
  printf("number of blank spaces: %d\n", spaces);
  printf("number of lines: %d\n", lines);
  printf("number of characters: %d\n", characters);
  return 0;
}
int yywrap() {
  return 1;
}
Input file/code-
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void loop()
{
  int i, j = 5;
  for (int i = 0; i < j; i++)
  {
        printf("%d. Hi\n", (i + 1));
    }
}
int main()
{
  double a = -3.14;
  char at = '@', tab = '\t';
    loop();
    return 0;
}
Ques-7 Write a Lex specification program that generates a C program
which takes a string “abcd”
and prints the following output.
abcd
abc
ab
a
Solution-
%option noyywrap
%{
 #include <stdio.h>
%}
%%
a|ab|abc|abcd { printf("%s\n", yytext); REJECT; }
.|\n { ; }
%%
int main() {
  yyin = fopen("input.txt", "r");
  yylex();
  return 0;
}
Input file-
Output-
Ques-8 A program in Lex to recognize a valid arithmetic expression.
Solution-
%{
 #include <stdio.h>
 int brackets = 0,
   operators = 0,
   numbersOridentifiers = 0,
   flag = 0;
%}
%%
[a-zA-Z_]+[a-zA-Z0-9_]* { numbersOridentifiers++; }
-?[0-9]+("."[0-9]+)? { numbersOridentifiers++; }
[+|\-|*|/|=|\^|%] { operators++; }
"(" { brackets++; }
")" { brackets--; }
";" { flag = 1; }
.|\n { ; }
%%
int main() {
  printf("\nEnter Arithmetic Expression: ");
  /* yyin = fopen("input.txt", "r"); */
  yylex();
  if (
    (operators + 1) == numbersOridentifiers
     && brackets == 0 && flag == 0
  ){
    printf("Valid Expression\n");
  } else {
    printf("Invalid Expression\n");
  }
  return 0;
}
int yywrap() {
  return 1;
}
Output
Ques-9 writes a yacc program to verify an expression as valid or not.
Solution-
first.y
%{
  #include<stdio.h>
  #include<stdlib.h>
  int flag = 0;
%}
%token ID
%token NUMBER
%left '+' '-'
%left '*' '/' '%'
%%
stmt : expr {
   printf("Result=%d \n",$$);
   return 0;
};
expr : expr'+'expr {$$ = $1 + $3;} |
     expr'-'expr {$$ = $1 - $3;} |
     expr'*'expr {$$ = $1 * $3;} |
     expr'/'expr {$$ = $1 / $3;} |
     '('expr')' {$$ = $2;} |
     ID {$$ = $1;} |
     NUMBER {$$ = $1;}
     ;
%%
int main(){
   printf("enter expr: \n");
   yyparse();
   if(flag == 0){
      printf("Valid expression");
   }
}
int yyerror(){
   printf("Error \n");
    flag = 1;
}
yacc.l
%{
  #include<stdio.h>
  #include "first.tab.c"
  extern int yylval;
%}
%%
[0-9]+ {
   yylval = atoi(yytext);
   return NUMBER;
}
[a-zA-Z]+ {
   yylval = yytext;
   return ID;
}
[\n] {return 0;}
. return yytext[0];
%%
int yywrap(){
   return 1;
}
Que10. A Program in YACC which recognizes a valid variable
which starts with letter followed by a digit. The letter should be in
lowercase only.
#p10.l
%{
  #include "p10.tab.c"
%}
%%
[a-zA-Z_][a-zA-Z_0-9]* return letter;
[0-9]                 return digit;
.              return yytext[0];
\n                 return 0;
%%
int yywrap()
return 1;
#P10.y
%{
    #include<stdio.h>
    int valid=1;
%}
%token digit letter
%%
start : letter s
s:        letter s
      | digit s
%%
int yyerror()
     printf("\nIts not a identifier!\n");
     valid=0;
     return 0;
}
int main()
    printf("\nEnter a name to tested for identifier ");
    yyparse();
    if(valid)
        printf("\nIt is a identifier!\n");
}
Que11. A Program in YACC to evaluate an expression (simple
calculator program for addition and subtraction, multiplication,
division).
#p11.l
%{
 #include <stdio.h>
 #include "p11.tab.c"
 extern int yylval;
%}
%%
[0-9]+ {
 yylval = strtol(yytext,NULL,0);
 return NUMBER;
}
\n {return 0;}
. {return yytext[0];}
%%
int yywrap() {
 return 1;
}
#p11.y
%{
 #include <stdio.h>
 #include <stdlib.h>
%}
%token NUMBER
%left '+' '-'
%left '*' '/'
%left '(' ')'
%%
stmt:e {printf("\nresult : %d",$$);}
e: e '+' e {$$ = $1 + $3;}
 | e '-' e {$$ = $1 - $3;}
 | e '*' e {$$ = $1 * $3;}
 | e '/' e {$$ = $1 / $3;}
 | '(' e ')' {$$ = $2;}
 | NUMBER ;
%%
int main(){
 printf("Enter expression (+ / * - %) : ");
 yyparse();
 printf("\nValid expression :)");
 return 0;
}
int yyerror(){
 printf("\nInvalid expression :(");
 return 0;
}
Que12. Program in YACC to recognize the strings “ab”, “aabb”,
”aaabbb”,… of the language (𝑎𝑛 𝑏𝑛 , n>=1).
#p12.l
%{
 #include "p12.tab.c"
%}
%%
[aA] {return A;}
[bB] {return B;}
\n {return NL;}
. {return yytext[0];}
%%
int yywrap(){
 return 1;
}
#p12.y
%{
 #include<stdio.h>
 #include<stdlib.h>
%}
%token A B NL
%%
stmt: S NL { printf("valid string\n"); exit(0); } ;
S: A S B | ;
%%
int yyerror(char *msg) {
 printf("invalid string\n");
 exit(0);
}
main() {
 printf("enter the string\n");
 yyparse();
}
Que13. Program in YACC to recognize the language (𝑎𝑛𝑏 ,
n>=10). (Output to say input is valid or not)
#p13.l
%{
 #include "p13.tab.c"
 extern int yylval;
%}
A [a]{10,}
B [b]
%%
{A} {yylval=yytext[0];return A;}
{B} {yylval=yytext[1];return B;}
\n {return 0;}
. {return yytext[0];}
%%
int yywrap(){
 return 1;
}
#p13.y
%{
 #include<stdio.h>
 #include<stdlib.h>
 int yylex(void);
%}
%token A B
%%
expr: s B {printf("\n valid string");};
s:sA|A;
%%
int main(){
 printf(" Enter the string \n");
 yyparse();
 return 0;
}
int yyerror(){
 printf(" Invalid: Not a part of the language - a^n b \n");
}