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

CD Lab Programs

The document consists of multiple C programming labs focusing on different aspects of programming language concepts, including token recognition, parsing, grammar analysis, and syntax error handling. Each lab implements specific functionalities such as identifying keywords, operators, and grammar transformations like left recursion removal and left factoring. Overall, the labs provide practical exercises in compiler design and language processing.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views19 pages

CD Lab Programs

The document consists of multiple C programming labs focusing on different aspects of programming language concepts, including token recognition, parsing, grammar analysis, and syntax error handling. Each lab implements specific functionalities such as identifying keywords, operators, and grammar transformations like left recursion removal and left factoring. Overall, the labs provide practical exercises in compiler design and language processing.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

//lab 1

#include <stdio.h>
#include <ctype.h>
#include <string.h>

/* Function to check keyword */


int isKeyword(char str[])
{
char *keywords[] = {
"int", "float", "if", "else",
"while", "return", "char"
};

int i;

for(i = 0; i < 7; i++)


{
if(strcmp(str, keywords[i]) == 0)
return 1;
}

return 0;
}

/* Function to check identifier */


int isIdentifier(char str[])
{
int i;

if(isalpha(str[0]) || str[0] == '_')


{
for(i = 1; str[i] != '\0'; i++)
{
if(!isalnum(str[i]) && str[i] != '_')
return 0;
}
return 1;
}

return 0;
}

/* Function to check number */


int isNumber(char str[])
{
int i;

for(i = 0; str[i] != '\0'; i++)


{
if(!isdigit(str[i]))
return 0;
}

return 1;
}

int main()
{
char input[200], token[50];
int i = 0, j;

printf("Enter a string:\n");
fgets(input, sizeof(input), stdin);

printf("\nTokens and their Types:\n\n");

while(input[i] != '\0')
{
/* Skip spaces */
if(isspace(input[i]))
{
i++;
continue;
}

j = 0;

/* Identifier or Keyword */
if(isalpha(input[i]) || input[i] == '_')
{
while(isalnum(input[i]) || input[i] == '_')
{
token[j++] = input[i++];
}

token[j] = '\0';

if(isKeyword(token))
printf("%-15s --> Keyword\n", token);
else if(isIdentifier(token))
printf("%-15s --> Identifier\n", token);
}

/* Number */
else if(isdigit(input[i]))
{
while(isdigit(input[i]))
{
token[j++] = input[i++];
}

token[j] = '\0';

if(isNumber(token))
printf("%-15s --> Number\n", token);
}

/* Operators */
else if(strchr("+-*/=<>", input[i]))
{
printf("%-15c --> Operator\n", input[i]);
i++;
}

/* Special Symbols */
else if(strchr("();{},[]", input[i]))
{
printf("%-15c --> Special Symbol\n", input[i]);
i++;
}

/* Invalid Token */
else
{
printf("%-15c --> Invalid Token\n", input[i]);
i++;
}
}

return 0;
}
//lab2
#include <stdio.h>
#include <string.h>

int main()
{
char arithmetic[] = {'+','-','*','/','%'};
char relational[] = {'<','>','!','='};
char bitwise[] = {'&','^','~','|'};
char str[4];

printf("Enter value to be identified: ");


scanf("%s", str);

int i;

/* Logical Operators */
if (((str[0]=='&' || str[0]=='|') &&
str[0]==str[1] &&
str[2]=='\0') ||
(str[0]=='!' && str[1]=='\0'))
{
printf("\nIt is Logical Operator");
}

/* Relational Operators */
for(i=0;i<4;i++)
{
if(str[0]==relational[i] &&
(str[1]=='=' || str[1]=='\0'))
{
printf("\nIt is Relational Operator");
break;
}
}

/* Bitwise Operators */
for(i=0;i<4;i++)
{
if((str[0]==bitwise[i] && str[1]=='\0') ||
((str[0]=='<' || str[0]=='>') &&
str[1]==str[0] &&
str[2]=='\0'))
{
printf("\nIt is Bitwise Operator");
break;
}
}

/* Arithmetic / Unary / Assignment */


for(i=0;i<5;i++)
{
if((str[0]=='+' || str[0]=='-') &&
str[0]==str[1] &&
str[2]=='\0')
{
printf("\nIt is Unary Operator");
break;
}
else if((str[0]==arithmetic[i] && str[1]=='=') ||
(str[0]=='=' && str[1]=='\0'))
{
printf("\nIt is Assignment Operator");
break;
}
else if(str[0]==arithmetic[i] && str[1]=='\0')
{
printf("\nIt is Arithmetic Operator");
break;
}
}

return 0;
}
//lab3
%{
#include<stdio.h>
%}

letter [A-Za-z]
uppercase [A-Z]
lowercase [a-z]
digit [0-9]
identifier {letter}({letter}|{digit})*

%%

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

{identifier} { printf("Identifier: %s\n", yytext); }

{digit}+ { printf("Number: %s\n", yytext); }

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

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

{uppercase} { printf("Uppercase Letter: %s\n", yytext); }

{lowercase} { printf("Lowercase Letter: %s\n", yytext); }

{digit} { printf("Digit: %s\n", yytext); }

[ \t\n]+ ; /* Ignore whitespace */

. { printf("Unknown Character: %s\n", yytext); }

%%

int yywrap()
{
return 1;
}

int main()
{
printf("Enter input:\n");
yylex();
return 0;
}

%{
#include<stdio.h>
#include<ctype.h>
int tokens = 0;
int uc = 0, lc = 0, dg = 0;

/* Function to count uppercase, lowercase and digits */


void count_chars(char *str)
{
int i;
for(i = 0; str[i] != '\0'; i++)
{
if(isupper(str[i]))
uc++;
else if(islower(str[i]))
lc++;
else if(isdigit(str[i]))
dg++;
}
}
%}

letter [A-Za-z]
digit [0-9]
identifier {letter}({letter}|{digit})*

%%

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

{identifier}
{
printf("Identifier : %s\n", yytext);
tokens++;
count_chars(yytext);
}

{digit}+
{
printf("Number : %s\n", yytext);
tokens++;
count_chars(yytext);
}

"+"|"-"|"*"|"/"|"="|"=="|"<"|">"|"<="|">="|"!="
{
printf("Operator : %s\n", yytext);
tokens++;
count_chars(yytext);
}

";"|","|"("|")"|"{"|"}"|"["|"]"
{
printf("Special Symbol : %s\n", yytext);
tokens++;
count_chars(yytext);
}

[ \t\n]+ ;

.
{
printf("Unknown Token : %s\n", yytext);
tokens++;
count_chars(yytext);
}

%%

int yywrap()
{
return 1;
}

int main()
{
printf("Enter the input:\n");

yylex();

printf("\n========== SUMMARY ==========\n");


printf("Total Tokens : %d\n", tokens);
printf("Uppercase Letters : %d\n", uc);
printf("Lowercase Letters : %d\n", lc);
printf("Digits : %d\n", dg);
printf("Total Letters : %d\n", uc + lc);

return 0;
}
//lab 4
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
char look_ahead;
void E();
void E1();
void T();
void T1();
void F();
void match(char c);
void E(){
T();
E1();
}
void E1(){
if(look_ahead=='+'){
match('+');
T();
E1();
}
else
return;
}
void T(){
F();
T1();
}
void T1(){
if(look_ahead=='*'){
match('*');
F();
T1();
}
else
return;
}
void F(){
if(look_ahead=='('){
match('(');
E();
match(')');
}
else if(look_ahead=='i')
match('i');
else{
printf("Error!\n");
exit(0);
}
}
void match(char c){
if(look_ahead==c)
look_ahead=getchar();
else{
printf("Error!\n");
exit(0);
}
}
int main(){
look_ahead=getchar();
E();
if(look_ahead=='$')
printf("Parsing Successful");
else
printf("NO");
return 0;
}
// lab 5
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int n, m = 0;
char a[10][10], f[10];

void follow(char c);


void first(char c);
void add(char c);

int main() {
int i, z;
char c;

printf("Enter the number of productions:\n");


scanf("%d", &n);

printf("Enter productions (e.g S=AB):\n");


for (i = 0; i < n; i++)
scanf("%s", a[i]);

do {
m = 0;

printf("Enter element: ");


scanf(" %c", &c);

first(c);
printf("First(%c) = { ", c);
for (i = 0; i < m; i++)
printf("%c ", f[i]);
printf("}\n");

m = 0;

follow(c);
printf("Follow(%c) = { ", c);
for (i = 0; i < m; i++)
printf("%c ", f[i]);
printf("}\n");

printf("Continue (1/0): ");


scanf("%d", &z);

} while (z == 1);

return 0;
}

void add(char c) {
int k;
for (k = 0; k < m; k++) {
if (f[k] == c)
return;
}
f[m++] = c;
}

void first(char c) {
int k;

if (!isupper(c)) {
add(c);
return;
}

for (k = 0; k < n; k++) {


if (a[k][0] == c) {
if (a[k][2] == '#')
add('#');
else if (!isupper(a[k][2]))
add(a[k][2]);
else
first(a[k][2]);
}
}
}

void follow(char c) {
int i, j;

if (a[0][0] == c)
add('$');

for (i = 0; i < n; i++) {


for (j = 2; j < strlen(a[i]); j++) {
if (a[i][j] == c) {
if (a[i][j + 1] != '\0') {
first(a[i][j + 1]);
}

if (a[i][j + 1] == '\0' && c != a[i][0]) {


follow(a[i][0]);
}
}
}
}
}
//lab-6
#include <stdio.h>
#include <string.h>

int main()
{
char grammar[50];
char rhs[10][20];
char nonterminal;
int i, j = 0, k = 0, n = 0;
int leftRecursion = 0;

printf("Enter the grammar (Example: A->Aa|b): ");


scanf("%s", grammar);

nonterminal = grammar[0];

// Extract RHS productions


for (i = 3; grammar[i] != '\0'; i++)
{
if (grammar[i] == '|')
{
rhs[n][k] = '\0';
n++;
k = 0;
}
else
{
rhs[n][k++] = grammar[i];
}
}
rhs[n][k] = '\0';
n++;

// Check for left recursion


for (i = 0; i < n; i++)
{
if (rhs[i][0] == nonterminal)
{
leftRecursion = 1;
break;
}
}

if (leftRecursion)
{
printf("\nLeft Recursion is present\n");
printf("Grammar after removing Left Recursion:\n");

// A -> βA'
printf("%c -> ", nonterminal);
for (i = 0; i < n; i++)
{
if (rhs[i][0] != nonterminal)
{
printf("%s%c'", rhs[i], nonterminal);
if (i != n - 1)
printf(" | ");
}
}

// A' -> αA' | ε


printf("\n%c' -> ", nonterminal);
for (i = 0; i < n; i++)
{
if (rhs[i][0] == nonterminal)
{
printf("%s%c'", rhs[i] + 1, nonterminal);
printf(" | ");
}
}
printf("ε\n");
}
else
{
printf("\nNo Left Recursion found\n");
}

// -------- LEFT FACTORING --------

int leftFactoring = 1;
char common = rhs[0][0];

for (i = 1; i < n; i++)


{
if (rhs[i][0] != common)
{
leftFactoring = 0;
break;
}
}

if (leftFactoring && n > 1)


{
printf("\nLeft Factoring is present\n");
printf("Grammar after Left Factoring:\n");

// A -> aA'
printf("%c -> %c%c'\n", nonterminal, common, nonterminal);

// A' -> rest


printf("%c' -> ", nonterminal);
for (i = 0; i < n; i++)
{
printf("%s", rhs[i] + 1);
if (i != n - 1)
printf(" | ");
}
printf("\n");
}
else
{
printf("\nNo Left Factoring found\n");
}
return 0;
}
//lab=07
#include <stdio.h>
#include <string.h>

char a[100];
int top = -1, i;

void error() {
printf("\nSyntax Error\n");
}

void push(char k[]) {


for (i = strlen(k) - 1; i >= 0; i--) {
if (top < 99)
a[++top] = k[i];
}
}

char TOS() {
if (top >= 0)
return a[top];
return '\0';
}

void pop() {
if (top >= 0)
a[top--] = '\0';
}

void display() {
int j;
for (j = 0; j <= top; j++)
printf("%c", a[j]);
}

void displayi(char p[], int m) {


int l;
printf("\t");
for (l = m; p[l] != '\0'; l++)
printf("%c", p[l]);
}

int main() {
char ip[50], r[20], st, an;
int ir, ic, j = 0;
int flag = 0;

char t[5][6][10] = {
{"err", "err", "TH", "err", "TH", "err"},
{"+TH", "err", "e", "e", "err", "e"},
{"err", "err", "FU", "err", "FU", "err"},
{"e", "*FU", "e", "e", "err", "e"},
{"err", "err", "(E)", "err", "i", "err"}
};

printf("Grammar:\n");
printf("E -> TH\n");
printf("H -> +TH | e\n");
printf("T -> FU\n");
printf("U -> *FU | e\n");
printf("F -> (E) | i\n");

printf("\nEnter any String(Append with $): ");


scanf("%s", ip);

printf("\nStack\tInput\tOutput\n\n");

push("$");
push("E");

display();
printf("\t%s\n", ip);

while (top >= 0) {

st = TOS();
an = ip[j];

/* Convert identifiers to i */
if ((an >= 'a' && an <= 'z') || (an >= 'A' && an <= 'Z'))
an = 'i';

/* Matching terminal */
if (st == an) {
pop();

display();
displayi(ip, j + 1);

printf("\tPOP\n");

j++;
}
else {

/* Row selection */
if (st == 'E')
ir = 0;
else if (st == 'H')
ir = 1;
else if (st == 'T')
ir = 2;
else if (st == 'U')
ir = 3;
else if (st == 'F')
ir = 4;
else {
error();
flag = 1;
break;
}

/* Column selection */
if (an == '+')
ic = 0;
else if (an == '*')
ic = 1;
else if (an == '(')
ic = 2;
else if (an == ')')
ic = 3;
else if (an == 'i')
ic = 4;
else if (an == '$')
ic = 5;
else {
error();
flag = 1;
break;
}

strcpy(r, t[ir][ic]);

/* Error entry */
if (strcmp(r, "err") == 0) {
error();
flag = 1;
break;
}

pop();

/* epsilon production */
if (strcmp(r, "e") != 0)
push(r);

display();
displayi(ip, j);

if (strcmp(r, "e") == 0)
printf("\t%c -> e\n", st);
else
printf("\t%c -> %s\n", st, r);
}
}

if (!flag && top == -1 && ip[j] == '\0')


printf("\nGiven String is accepted\n");
else
printf("\nGiven String is not accepted\n");

return 0;
}
//lab-8 Three Address Code
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>

#define max 200

char opstack[max];
char valstack[max][20];
int topop = -1, topval = -1, tempcount = 1;

int precedence(char op){


if(op == '+' || op == '-') return 1;
if(op == '*' || op == '/') return 2;
return 0;

void pushop(char op){


opstack[++topop] = op;
}

char popop(){
return opstack[topop--];
}

void pushval(char *val){


strcpy(valstack[++topval],val);
}

void popval(char *val){


strcpy(val,valstack[topval--]);
}

void generate(){
char op = popop();
char op1[20], op2[20], temp[20];
popval(op1);
popval(op2);
sprintf(temp , "t%d", tempcount++);
printf("%s = %s%c%s \n", temp, op1,op, op2);
pushval(temp);
}

int main(){

char exp[max];
printf("enter an expression : ");
scanf("%s",exp);

for(int i =0; exp[i] != '\0'; i++){


char ch = exp[i];
if(isalnum(ch)){
char operand[2] = {ch, '\0'};
pushval(operand);
}
else if(ch == '('){
pushop(ch);
}
else if(ch == ')'){
while(opstack[topop] != '('){
generate();
}
popop();
}
else{
while(topop != -1 && precedence(opstack[topop]) >= precedence(ch)){
generate();
}
pushop(ch);
}
}

while(topop != -1){
generate();
}
return 0;

You might also like