0% found this document useful (0 votes)
28 views19 pages

CD Lab Answers

Uploaded by

gayathri1662004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views19 pages

CD Lab Answers

Uploaded by

gayathri1662004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 19

1)

#include<string.h>
#include<conio.h>
#include<ctype.h>
#include<stdio.h>
int main()
{
FILE *f1;
char c,str[10];
int lineno=1,num=0,i=0;
printf("\nEnter the c program\n");
f1=fopen("input.txt","w");
while((c=getchar())!=EOF)
putc(c,f1);
fclose(f1);
f1=fopen("input.txt","r");
while((c=getc(f1))!=EOF)
{
if(isdigit(c))
{
num=c-48;
c=getc(f1);
while(isdigit(c))
{
num=num*10+(c-48);
c=getc(f1);
}
printf("%d is a number \n",num);
ungetc(c,f1);
}
else if(isalpha(c))
{
str[i++]=c;
c=getc(f1);
while(isdigit(c)||isalpha(c)||c=='_'||c=='$')
{
str[i++]=c;
c=getc(f1);
}
str[i++]='\0';
if(strcmp("for",str)==0||strcmp("while",str)==0||strcmp("do",str)==0||
strcmp("int",str)==0||strcmp("float",str)==0||strcmp("char",str)==0||
strcmp("double",str)==0||strcmp("static",str)==0||
strcmp("switch",str)==0||strcmp("case",str)==0)
printf("%s is a keyword\n",str);
else
printf("%s is a identifier\n",str);
ungetc(c,f1);
i=0;
}
else if(c==' '||c=='\t')
printf("\n");
else if(c=='\n')
lineno++;
else
printf("%c is a special symbol\n",c);
}
printf("Total no. of lines are: %d\n",lineno);
fclose(f1);
getch();
}

OUTPUT:

Enter the c program


int main()
{
int a=10,20;
charch;
float f;
}^Z
The numbers in the program are: 10 20
The keywords and identifiers are:
int is a keyword
main is an identifier
int is a keyword
a is an identifier
char is a keyword
ch is an identifier
float is a keyword
f is an identifier
Special characters are ( ) { = , ; ; ; }
Total no. of lines are:5
___________________________________________________________________________________
______________________________________________________________

2)

%
{
int count = 0;
%
}
%%
[A-Z] {printf("%s capital letter\n", yytext);
count++;}
. {printf("%s not a capital letter\n", yytext);}
\n {return 0;}
%%

int yywrap(){}
int main(){

yylex();
printf("\nNumber of Capital letters "
"in the given input - %d\n", count);

return 0;
}

(OR)

%{
#include <stdio.h>
#include <ctype.h>
%}

%option noyywrap

%%
[ \t\n]+ { /* Ignore whitespaces */ }

"//".* { /* Ignore single-line comments */ }

"/*"([^*]|\*+[^*/])*\*+"/" { /* Ignore multi-line comments */ }

int|float|if|else|while|return|char { printf("Keyword: %s\n", yytext); }

[a-zA-Z_][a-zA-Z0-9_]* { printf("Identifier: %s\n", yytext); }

[0-9]+ { printf("Number: %s\n", yytext); }

"="|"<"|">"|"<="|">="|"=="|"!="|"\+"|"-"|"*"|"/" { printf("Operator: %s\n",


yytext); }

"(" | ")" | "{" | "}" | ";" | "," | "[" | "]" { printf("Delimiter: %s\n",
yytext); }

. { printf("Unrecognized character: %s\n", yytext); }

%%
int main()
{
printf("Enter the source code:\n");
yylex();
return 0;
}

Output:

int main() {
// This is a comment
int a = 10;
float b = 20.5;
a = a + b;
/* Multi-line
comment */
return 0;
}
Enter the source code:
Keyword: int
Identifier: main
Delimiter: (
Delimiter: )
Delimiter: {
Keyword: int
Identifier: a
Operator: =
Number: 10
Delimiter: ;
Keyword: float
Identifier: b
Operator: =
Number: 20
Delimiter: ;
Identifier: a
Operator: =
Identifier: a
Operator: +
Identifier: b
Delimiter: ;
Keyword: return
Number: 0
Delimiter: ;
Delimiter: }

___________________________________________________________________________________
__________________________________

3--In manual 3a)


___________________________________________________________________________________
______________________________

4--In manual 3d)


___________________________________________________________________________________
______________________________

5--In manual 3b)


___________________________________________________________________________________
_______________________________

6)
%{
#include <stdio.h>
%}

%%

abc { printf("ABC"); }
. { putchar(yytext[0]); }
\n { putchar('\n'); }
%%

int main() {
printf("Enter a string: ");
yylex();
return 0;
}

int yywrap() {
return 1;
}

(OR)

%{
#include
#include
int i;
%}
%%
[a-z A-Z]* {
for(i=0;i<=yyleng;i++)
{
if((yytext[i]=='a')&&(yytext[i+1]=='b')&&(yytext[i+2]=='c'))
{
yytext[i]='A';
yytext[i+1]='B';
yytext[i+2]='C';
}
}
printf("%s",yytext);
}
[\t]* return;
.* {ECHO;}
\n {printf("%s",yytext);}
%%
main()
{
yylex();
}
int yywrap()
{
return 1;
}

___________________________________________________________________________________
____________________________________________________

7)
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int isIdentifier(const char *input) {
if (!isalpha(input[0]) && input[0] != '_') {
return 0;
}
for (int i = 1; input[i] != '\0'; i++) {
if (!isalnum(input[i]) && input[i] != '_') {
return 0;
}
}
return 1;
}
int isConstant(const char *input) {
int hasDecimal = 0;
for (int i = 0; input[i] != '\0'; i++) {
if (input[i] == '.') {
if (hasDecimal) {
return 0;
}
hasDecimal = 1;
} else if (!isdigit(input[i])) {
return 0;
}
}
return 1;
}
int isOperator(const char *input) {
const char *operators[] = {"+", "-", "*", "/", "=", "==", "!=", "<", ">", "<=",
">="};
const int numOperators = 11;
for (int i = 0; i < numOperators; i++) {
if (strcmp(input, operators[i]) == 0) {
return 1;
}
}
return 0;
}
int main() {
char input[100];

printf("Enter a token: ");


scanf("%s", input);

if (isIdentifier(input)) {
printf("The token is an Identifier.\n");
} else if (isConstant(input)) {
printf("The token is a Constant.\n");
} else if (isOperator(input)) {
printf("The token is an Operator.\n");
} else {
printf("The token is invalid or unrecognized.\n");
}

return 0;
}

Output:
Enter a token: abc123
The token is an Identifier.
Enter a token: @
The token is invalid or unrecognized.

___________________________________________________________________________________
________________________________________________________

8)
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int isIdentifier(const char *input) {
int state = 0;
for (int i = 0; input[i] != '\0'; i++) {
char c = input[i];
switch (state) {
case 0:
if (isalpha(c) || c == '_') {
state = 1;
} else {
return 0;
}
break;
case 1:
if (isalnum(c) || c == '_') {
state = 1;
} else {
return 0;
}
break;
}
}
return state == 1;
}
int isConstant(const char *input) {
int state = 0, hasDecimal = 0;
for (int i = 0; input[i] != '\0'; i++) {
char c = input[i];
switch (state) {
case 0:
if (isdigit(c)) {
state = 1;
} else if (c == '.') {
hasDecimal = 1;
state = 2;
} else {
return 0;
}
break;
case 1:
if (isdigit(c)) {
state = 1;
} else if (c == '.' && !hasDecimal) {
hasDecimal = 1;
state = 2;
} else {
return 0;
}
break;
case 2:
if (isdigit(c)) {
state = 2;
} else {
return 0;
}
break;
}
}
return state == 1 || state == 2;
}
int isOperator(const char *input) {
const char *operators[] = {"+", "-", "*", "/", "=", "==", "!=", "<", ">", "<=",
">="};
const int numOperators = 11;
for (int i = 0; i < numOperators; i++) {
if (strcmp(input, operators[i]) == 0) {
return 1;
}
}
return 0;
}
int main() {
char input[100];

printf("Enter a token: ");


scanf("%s", input);
if (isIdentifier(input)) {
printf("The token is an Identifier.\n");
} else if (isConstant(input)) {
printf("The token is a Constant.\n");
} else if (isOperator(input)) {
printf("The token is an Operator.\n");
} else {
printf("The token is invalid or unrecognized.\n");
}

return 0;
}
Output:

Enter a token: ==
The token is an Operator.
Enter a token: 45
The token is a Constant.

___________________________________________________________________________________
____________

9)---In manual 6)
___________________________________________________________________________________
____________

10---In manual 7)
___________________________________________________________________________________
____________

11)
%{
int vow_count=0;
int const_count =0;
%}

%%
[aeiouAEIOU] {vow_count++;}
[a-zA-Z] {const_count++;}
%%
int yywrap(){}
int main()
{
printf("Enter the string of vowels and consonants:");
yylex();
printf("Number of vowels are: %d\n", vow_count);
printf("Number of consonants are: %d\n", const_count);
return 0;
}

Output:

Enter the string of vowels and consonents: programminglanguage


The number of vowels are:6
The number of consonants are:12
___________________________________________________________________________________
__________________________________________

12)
#include <stdio.h>
#include <string.h>
int isValidForLoop(const char *input) {
return strstr(input, "for(") != NULL && strstr(input, ";") != NULL;
}
int isValidWhileLoop(const char *input) {
return strstr(input, "while(") != NULL && strchr(input, ')') != NULL;
}

int main() {
char input[256];

printf("Enter a control structure: ");


fgets(input, sizeof(input), stdin);
input[strcspn(input, "\n")] = '\0';

if (isValidForLoop(input)) {
printf("The input is a valid 'for' loop.\n");
} else if (isValidWhileLoop(input)) {
printf("The input is a valid 'while' loop.\n");
} else {
printf("The input is not a valid 'for' or 'while' loop.\n");
}

return 0;
}

Output:
Enter a control structure: for(i = 0; i < 10; i++)
The input is a valid 'for' loop.
Enter a control structure: while(x > 0)
The input is a valid 'while' loop.
Enter a control structure: if(x > 0)
The input is not a valid 'for' or 'while' loop.

___________________________________________________________________________________
_______________________________________

13)%{
#include <stdio.h>
#include <stdlib.h>
typedef struct ASTNode {
char* value;
struct ASTNode* left;
struct ASTNode* right;
} ASTNode;
ASTNode* createNode(char* value, ASTNode* left, ASTNode* right) {
ASTNode* node = (ASTNode*)malloc(sizeof(ASTNode));
node->value = value;
node->left = left;
node->right = right;
return node;
}

void printAST(ASTNode* node, int level) {


if (node == NULL) return;
for (int i = 0; i < level; i++) printf(" ");
printf("%s\n", node->value);
printAST(node->left, level + 1);
printAST(node->right, level + 1);
}
%}

%token NUMBER
%left '+' '-'
%left '*' '/'

%%
expression:
expression '+' term {
$$ = createNode("+", $1, $3);
}
| expression '-' term {
$$ = createNode("-", $1, $3);
}
| term {
$$ = $1;
}
;

term:
term '*' factor {
$$ = createNode("*", $1, $3);
}
| term '/' factor {
$$ = createNode("/", $1, $3);
}
| factor {
$$ = $1;
}
;

factor:
'(' expression ')' {
$$ = $2;
}
| NUMBER {
$$ = createNode("NUMBER", NULL, NULL);
}
;

%%
int yylex() {
char ch = getchar();
if (ch == EOF) return 0;
if (ch >= '0' && ch <= '9') {
ungetc(ch, stdin);
scanf("%d", &yylval);
return NUMBER;
}
return ch;
}

void yyerror(const char *s) {


fprintf(stderr, "Error: %s\n", s);
}

int main() {
printf("Enter an expression: ");
yyparse();
return 0;
}

Output:

Enter an expression: 3 + 5 * (2 - 1)
+
NUMBER
3
*
NUMBER
5
-
NUMBER
2
NUMBER
1

___________________________________________________________________________________
__________________________________________

14)
#include <stdio.h>
#include <string.h>
int isValidIfElse(const char *input) {
return strstr(input, "if(") != NULL && strstr(input, "else") != NULL;
}
int isValidIfElseIf(const char *input) {
return strstr(input, "if(") != NULL && strstr(input, "else if(") != NULL &&
strstr(input, "else") != NULL;
}
int isValidSwitchCase(const char *input) {
return strstr(input, "switch(") != NULL && strstr(input, "case") != NULL &&
strstr(input, "default:") != NULL;
}
int main() {
char input[512];
printf("Enter a control structure: ");
fgets(input, sizeof(input), stdin);
input[strcspn(input, "\n")] = '\0';
if (isValidIfElseIf(input))
{
printf("The input is a valid 'if-else-if' structure.\n");
} else if (isValidIfElse(input))
{
printf("The input is a valid 'if-else' structure.\n");
} else if (isValidSwitchCase(input))
{
printf("The input is a valid 'switch-case' structure.\n");
} else
{
printf("The input is not a valid 'if-else', 'if-else-if', or 'switch-case'
structure.\n");
}

return 0;
}

Output:
Enter a control structure: if(x > 0) { printf("Positive"); } else
{ printf("Negative"); }
The input is a valid 'if-else' structure.

Enter a control structure: for(int i = 0; i < 10; i++) { printf("%d", i); }


The input is not a valid 'if-else', 'if-else-if', or 'switch-case' structure.

___________________________________________________________________________________
____________________________

15)
#include <stdio.h>
#define MAX_BLOCKS 10
#define MAX_PROCESSES 10
void firstFit(int blockSizes[], int m, int processSizes[], int n) {
int allocation[MAX_PROCESSES];
for (int i = 0; i < n; i++) {
allocation[i] = -1;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (blockSizes[j] >= processSizes[i]) {
allocation[i] = j;
blockSizes[j] -= processSizes[i];
break;
}
}
}
printf("\nProcess No.\tProcess Size\tBlock No.\n");
for (int i = 0; i < n; i++) {
printf("%d\t\t%d\t\t", i + 1, processSizes[i]);
if (allocation[i] != -1) {
printf("%d\n", allocation[i] + 1);
} else {
printf("Not Allocated\n");
}
}
}
int main() {
int blockSizes[MAX_BLOCKS], processSizes[MAX_PROCESSES];
int m, n;
printf("Enter the number of memory blocks: ");
scanf("%d", &m);
printf("Enter the sizes of the memory blocks:\n");
for (int i = 0; i < m; i++) {
printf("Block %d size: ", i + 1);
scanf("%d", &blockSizes[i]);
}
printf("\nEnter the number of processes: ");
scanf("%d", &n);
printf("Enter the sizes of the processes:\n");
for (int i = 0; i < n; i++) {
printf("Process %d size: ", i + 1);
scanf("%d", &processSizes[i]);
}
firstFit(blockSizes, m, processSizes, n);

return 0;
}

Output:

Enter the number of memory blocks: 5


Enter the sizes of the memory blocks:
Block 1 size: 100
Block 2 size: 500
Block 3 size: 200
Block 4 size: 300
Block 5 size: 600

Enter the number of processes: 4


Enter the sizes of the processes:
Process 1 size: 212
Process 2 size: 417
Process 3 size: 112
Process 4 size: 426
Process No. Process Size Block No.
1 212 3
2 417 2
3 112 1
4 426 5

___________________________________________________________________________________
___________________________________________

16)---In manual 5)
___________________________________________________________________________________
__________________________________________

17)
#include<stdio.h>
#include<string.h>
struct op
{
char l;
char r[20];
}op[10],pr[10];
int main()
{
int a,i,k,j,n,z=0,m,q;
char *p,*l;
char temp,t;
char *tem;

printf("Enter the Number of Values:");


scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("left: ");
scanf(" %c",&op[i].l);
printf("right: ");
scanf(" %s",&op[i].r);
}
printf("Intermediate Code\n") ;
for(i=0;i<n;i++)
{
printf("%c=",op[i].l);
printf("%s\n",op[i].r);
}
for(i=0;i<n-1;i++)
{
temp=op[i].l;
for(j=0;j<n;j++)
{
p=strchr(op[j].r,temp);
if(p)
{
pr[z].l=op[i].l;
strcpy(pr[z].r,op[i].
r);
z++;
}
}
}
pr[z].l=op[n-1].l;
strcpy(pr[z].r,op[n-1].r);
z++;
printf("\nAfter Dead Code Elimination\n");
for(k=0;k<z;k++)
{
printf("%c\t=",pr[k].l);
printf("%s\n",pr[k].r);
}
for(m=0;m<z;m++)
{
tem=pr[m].r;
for(j=m+1;j<z;j++)
{
p=strstr(tem,pr[j].r);
if(p)
{
t=pr[j].l;
pr[j].l=pr[m].l;
for(i=0;i<z;i++)
{
l=strchr(pr[i].r,t) ;
if(l)
{
a=l-pr[i].r;
printf("pos: %d\n",a);
pr[i].r[a]=pr[m].l;
}}}}}
printf("Eliminate Common Expression\n");
for(i=0;i<z;i++)
{
printf("%c\t=",pr[i].l);
printf("%s\n",pr[i].r);
}
for(i=0;i<z;i++)
{
for(j=i+1;j<z;j++)
{
q=strcmp(pr[i].r,pr[j].r);
if((pr[i].l==pr[j].l)&&!q)
{
pr[i].l='\0';
}
}
}
printf("Optimized Code\n");
for(i=0;i<z;i++)
{
if(pr[i].l!='\0')
{
printf("%c=",pr[i].l);
printf("%s\n",pr[i].r);
}
}
}

Output:
Enter the Number of Values:5
left: a
right: 9
left: b
right: c+d
left: e
right: c+d
left: f
right: b+e
left: r
right: f

Intermediate Code
a=9
b=c+d
e=c+d
f=b+e
r=f

After Dead Code Elimination


b =c+d
e =c+d
f =b+e
r =f
pos: 2
Eliminate Common Expression
b =c+d
b =c+d
f =b+b
r =f
Optimized Code
b=c+d
f=b+b
r=f
___________________________________________________________________________________
_______________________________________________________________________________
18)
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
int main()
{
int i=0,j=0,x=0,n;
void *p,*add[5];
char ch,srch,b[15],d[15],c;
printf("Expression terminated by $:");
while((c=getchar())!='$')
{
b[i]=c;
i++;
}
n=i-1;
printf("Given Expression:");
i=0;
while(i<=n)
{
printf("%c",b[i]);
i++;
}
printf("\n Symbol Table\n");
printf("Symbol \t addr \t type");
while(j<=n)
{
c=b[j];
if(isalpha(toascii(c)))
{
p=malloc(c);
add[x]=p;
d[x]=c;
printf("\n%c \t %d \t identifier\n",c,p);
x++;
j++;
}
else
{
ch=c;
if(ch=='+'||ch=='-'||ch=='*'||ch=='=')
{
p=malloc(ch);
add[x]=p;
d[x]=ch;
printf("\n %c \t %d \t operator\n",ch,p);
x++;
j++;
}
}
}
}

Output:
Expression terminated by $:A+B+C=d$
Given Expression:A+B+C=d
Symbol Table
Symbol addr type
A 10358192 identifier

+ 10358272 operator

B 10358328 identifier

+ 10358408 operator

C 10358464 identifier

= 10358544 operator

d 10358616 identifier
___________________________________________________________________________________
______________________________________________

19)
#include <stdio.h>
int main() {
int a, b;
int result;
printf("Enter value for a: ");
scanf("%d", &a);
printf("Enter value for b: ");
scanf("%d", &b);
result = 2 * a * b;
printf("The result of the optimized expression 2 * a * b is: %d\n", result);
return 0;
}

Output:
Enter value for a: 20
Enter value for b: 5
The result of the optimized expression 2 * a * b is: 200
-----------------------------------------------------------------------------------
--------------
20)
with LEX
%{
#include "y.tab.h"
%}

%option noyywrap

%%
[0-9]+ { yylval.iVal = atoi(yytext); return NUM; }
[a-zA-Z][a-zA-Z0-9]* { yylval.sVal = strdup(yytext); return ID; }
"+" { return PLUS; }
"-" { return MINUS; }
"*" { return MUL; }
"/" { return DIV; }
"=" { return ASSIGN; }
"(" { return LPAREN; }
")" { return RPAREN; }
"{" { return LBRACE; }
"}" { return RBRACE; }
";" { return SEMICOLON; }
[ \t\n] { /* Ignore spaces, tabs, and newlines */ }
. { return yytext[0]; }

%%

with YACC
%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int tempVarCount = 0;
void generateTAC(char *op, char *arg1, char *arg2, char *result) {
printf("%s = %s %s %s\n", result, arg1, op, arg2);
}
%}

%token NUM ID
%token PLUS MINUS MUL DIV ASSIGN
%token LPAREN RPAREN LBRACE RBRACE SEMICOLON

%%
program:
| program statement
;

statement:
expression SEMICOLON { printf("End of statement\n"); }
| declaration SEMICOLON { printf("End of declaration\n"); }
;

declaration:
ID ASSIGN expression { generateTAC("=", $3, "", $1); }
;

expression:
term { $$ = $1; }
| expression PLUS term { $$ = createTemp(); generateTAC("+", $1, $3, $$); }
| expression MINUS term { $$ = createTemp(); generateTAC("-", $1, $3, $$); }
;

term:
factor { $$ = $1; }
| term MUL factor { $$ = createTemp(); generateTAC("*", $1, $3, $$); }
| term DIV factor { $$ = createTemp(); generateTAC("/", $1, $3, $$); }
;

factor:
NUM { $$ = createTemp(); generateTAC("=", $1, "", $$); }
| ID { $$ = $1; }
| LPAREN expression RPAREN { $$ = $2; }
;

%%

char* createTemp() {
char *tempVar = (char *)malloc(10 * sizeof(char));
sprintf(tempVar, "t%d", tempVarCount++);
return tempVar;
}

int main() {
yyparse();
return 0;
}
Output:
a = 3;
b = 4;
c = a + b;
d = c * 5;
The generated Three Address Code would be:
t0 = 3
t1 = 4
t2 = t0 + t1
t3 = t2 * 5
___________________________________________________________________________________
__________________________

You might also like