This page contains code examples for the 21CSC304J Compiler Design course code
// Code for left factoring example
A → aB | aC becomes
A → aA'
A' → B | C
#include stdio.h// add < > this as it is not recognizing
#include string.h
int main() {
char non_terminal;
char beta, alpha;
int num;
char production[10][10];
int index = 3; /* starting of the string following "->" */
printf("Enter Number of Production : ");
scanf("%d", &num);
printf("Enter the grammar as E->E-A :\n");
for(int i = 0; i < num; i++) {
scanf("%s", production[i]);
}
for(int i = 0; i < num; i++) {
non_terminal = production[i][0];
index = 3; // Reset index for each production
if(non_terminal == production[i][index]) {
alpha = production[i][index + 1];
printf("%c is left recursive.\n", non_terminal);
// Find the end of the production
while(production[i][index] != '\0' && production[i][index] != '|') {
index++;
}
if(production[i][index] != '\0') {
beta = production[i][index + 1];}
// Eliminate left recursion
printf("Grammar without left recursion:\n");
printf("%c->%c%c\'\n", non_terminal, beta, non_terminal);
printf("%c\'->%cT%c\'|E\n", non_terminal, alpha, non_terminal);
}
else {
printf("%c is not left recursive.\n", non_terminal);
}
}
return 0;
}
// Code for eliminating left recursion
A → Aα | β becomes
A → βA'
A' → αA' | ε
#include stdio.h>
#include string.h>
int main()
{
char gram[50], part1[50], part2[50], modifiedGram[50], newGram[50];
int i, j = 0, k = 0, l = 0;
printf("Enter Production : A->");
scanf("%s", gram);
# // Find the length of the input
int len = strlen(gram);
for(i = 0; gram[i] != '|'; i++, j++){
part1[j] = gram[i];}
part1[j] = '\0';
for(j = i+1, i = 0; i < len; j++, i++){
part2[i] = gram[j];}
part2[i] = '\0';
# // Find the longest common prefix
for(i = 0; i < strlen(part1) && i < strlen(part2); i++)
{
if(part1[i] != part2[i])
break;
}
if(i > 0)
{
# // Store the common prefix in modifiedGram
for(j = 0; j < i; j++){
modifiedGram[j] = part1[j];}
modifiedGram[j] = 'X';
modifiedGram[++j] = '\0';
# // Store the remaining part of part1 in newGram
for(k = i, j = 0; part1[k] != '\0'; k++, j++)
newGram[j] = part1[k];
newGram[j++] = '|';
# // Store the remaining part of part2 in newGram
for(k = i; part2[k] != '\0'; k++, j++)
newGram[j] = part2[k];
}
else
{
printf("\nno common");
}
printf("\nGrammar Without Left Factoring:\n");
printf(" A->%s\n", modifiedGram);
printf(" X->%s\n", newGram);
return 0;
}
%{
%}
%%
[0-9]* {printf("This is a number");}
[a-z]* {printf("This is in lowercase");}
[A-Z]* {printf("This is in uppercase");}
.* {printf("unspecified rule");}
%%
int yywrap(){}
void main()
{
printf("Enter a string");
yylex();
}
#include iostream>
#include stack>
#include string>
using namespace std;
// Function to determine precedence of operators
int precedence(char op) {
switch (op) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return -1;
}
}
// Function to convert infix expression to postfix expression
string infixToPostfix(string infix) {
string postfix = "";
stack s;
for (int i = 0; i < infix.length(); i++) {
char ch = infix[i];
if (isdigit(ch)) {
postfix += ch;
} else {
while (!s.empty() && precedence(ch) <= precedence(s.top())) {
postfix += s.top();
s.pop();
}
s.push(ch);
}
}
while (!s.empty()) {
postfix += s.top();
s.pop();
}
return postfix;
}
// Function to evaluate postfix expression
int evaluatePostfix(string postfix) {
stack s;
for (int i = 0; i < postfix.length(); i++) {
char ch = postfix[i];
if (isdigit(ch)) {
s.push(ch - '0');//conver to string to int i.e 345
} else {
int operand2 = s.top(); s.pop();
int operand1 = s.top(); s.pop();
switch (ch) {
case '+':
s.push(operand1 + operand2);
break;
case '-':
s.push(operand1 - operand2);
break;
case '*':
s.push(operand1 * operand2);
break;
case '/':
s.push(operand1 / operand2);
break;
}
}
}
return s.top();
}
int main() {
string infixExpression = "3+4*5";
string postfixExpression = infixToPostfix(infixExpression);
cout << "Postfix expression: " << postfixExpression << endl;
int result = evaluatePostfix(postfixExpression);
cout << "Result: " << result << endl;
return 0;
}
%{
#include stdio.h>
int lc = 1; // Variable to count lines
int sc = 0; // Variable to count spaces
int cc = 0; // Variable to count characters
%}
%%
[ \t]+ { sc += yyleng; } /* Count spaces */
\n { lc++; } /* Count newlines */
"if" { printf ("IF\n"); cc += 2; }
"=" { printf ("ASSIGNMENT\n"); cc++; }
[-+*/()] { printf ("OPERATOR\n"); cc++; }
[0-9]+ { printf ("NUMBER\n"); cc += yyleng; }
[a-zA-Z_][a-zA-Z0-9_]* { printf ("IDENTIFIER\n"); cc += yyleng; }
. { printf ("SPECIAL_SYMBOL\n"); cc++; }
%%
int yywrap() {
return 1;
}
int main() {
yylex();
printf("Number of lines = %d\n", lc);
printf("Number of spaces = %d\n", sc);
printf("Number of characters = %d\n", cc);
return 0;
}
#include iostream>
#include string>
using namespace std;
// Example C++ function containing if and while constructs
void exampleFunction(int x, int y) {
int a = 0;
if (x > y) {
while (a < x) {
cout << "a is less than x" << endl;
a++;
}
} else {
cout << "x is not greater than y" << endl;
}
}
// Intermediate code generation for if statement
void generateIf(const string& condition, const string& trueLabel, const string& falseLabel) {
cout << "if (" << condition << ") goto " << trueLabel << ";" << endl;
cout << "goto " << falseLabel << ";" << endl;
cout << trueLabel << ":" << endl;
}
// Intermediate code generation for while loop
void generateWhile(const string& condition, const string& loopStartLabel, const string& loopEndLabel) {
cout << loopStartLabel << ":" << endl;
cout << "if (" << condition << ") goto " << loopEndLabel << ";" << endl;
}
int main() {
// Generating intermediate code for the example function
generateIf("x > y", "trueLabel1", "falseLabel1");
generateWhile("a < x", "loopStartLabel1", "loopEndLabel1");
cout << "cout << \"a is less than x\" << endl;" << endl;
cout << "a++;" << endl;
cout << "goto loopStartLabel1;" << endl;
cout << "loopEndLabel1:" << endl;
cout << "falseLabel1:" << endl;
cout << "cout << \"x is not greater than y\" << endl;" << endl;
return 0;
}
%{
%}
%%
[0-9]* {printf("This is a number");}
[a-z]* {printf("This is in lowercase");}
[A-Z]* {printf("This is in uppercase");}
.* {printf("unspecified rule");}
%%
int yywrap(){}
void main()
{
printf("Enter a string");
yylex();
}
!!!test.l!!!
%{
#include
#include
#include "nice.tab.h"
void showError();
%}
%%
[a-zA-Z]+ { sscanf(yytext, "%s", yylval.name); return STRING; }
[0-9]+ { yylval.number = atoi(yytext); return NUM; }
";" { return SEMICOLON; }
. { showError(); return OTHER; }
%%
void showError() {
printf("Other input\n");
}
int yywrap() {
return 1; // Indicates no more files to process
}
---------------------------------------------------------------
!!!test.y!!!
%{
#include
int yylex();
int yyerror(char *s);
%}
%token STRING NUM OTHER SEMICOLON
%type STRING
%type NUM
%union{
char name[20];
int number;
}
%%
prog:
stmts
;
stmts:
| stmt SEMICOLON stmts
stmt:
STRING {
printf("Your entered a string - %s", $1);
}
| NUM {
printf("The number you entered is - %d", $1);
}
| OTHER
;
%%
int yyerror(char *s)
{
printf("Syntax Error on line %s\n", s);
return 0;
}
int main()
{
yyparse();
return 0;
}
#include stdio.h>
#include string.h>
#include ctype.h>
int n;
char productions[10][10];
void findFirst(char c);
void findFollow(char c);
int main() {
int i;
char c, ch;
printf("Enter the number of productions: ");
scanf("%d", &n);
printf("Enter the productions:\n");
for (i = 0; i < n; i++)
scanf("%s", productions[i]);
printf("Enter the element whose FIRST & FOLLOW sets are to be found: ");
scanf(" %c", &c);
printf("FIRST(%c) = {", c);
findFirst(c);
printf("}\n");
printf("FOLLOW(%c) = {", c);
findFollow(c);
printf("}\n");
return 0;
}
void findFirst(char c) {
int i;
for (i = 0; i < n; i++) {
if (productions[i][0] == c) {
if (islower(productions[i][2]) || productions[i][2] == '$')
printf("%c", productions[i][2]);
else
findFirst(productions[i][2]);
}
}
}
void findFollow(char c) {
if (c == productions[0][0])
printf("$");
int i, j;
for (i = 0; i < n; i++) {
for (j = 2; j < strlen(productions[i]); j++) {
if (productions[i][j] == c) {
if (productions[i][j + 1] != '\0')
findFirst(productions[i][j + 1]);
else if (c != productions[i][0])
findFollow(productions[i][0]);
}
}
}
}
--------------------------------- ---------------------------
output:
Enter the number of productions: 1
Enter the productions:
E=a
Enter the element whose FIRST & FOLLOW sets are to be found: E
FIRST(E) = {a}
FOLLOW(E) = {$}
import java.util.Scanner;
class HelloWorld {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n;
n=sc.nextInt();
int fibo[] = new int[n + 1];
fibo[0] = 0;
fibo[1] = 1;
// Initialize sum
int sum = fibo[0] + fibo[1];
// Calculate Fibonacci sequence and sum
for (int i = 2; i < n; i++) {
fibo[i] = fibo[i - 1] + fibo[i - 2];
sum += fibo[i];
}
System.out.println("Sum of the first " + n + " Fibonacci numbers: " + sum);
}
}
=========================================================================================================
import java.util.Scanner;
class HelloWorld {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n;
n=sc.nextInt();
int maxa=0;
int[] arr = new int[n];
for(int i=0;imaxa){
maxa=arr[i];
}
}
System.out.println(maxa);
}
}
.data
num1: .word 10
num2: .word 5
.text
main:
# load num1 into $a0
lw $a0, num1
# load num2 into $a1
lw $a1, num2
# add num1 and num2
add $v0, $a0, $a1
# print result
li $v0, 1 # syscall code for print_int
syscall
# exit program
li $v0, 10 # syscall code for exit
syscall
Output: 15
run java progarm: C:\Users\priya>javac Name.java
C:\Users\priya>Name.java
public class Machinea {
public static void main(String[] args) {
// Create a byte array to store the machine code
byte[] machineCode = new byte[4];
// Set the opcode for the MIPS instruction in the byte array
machineCode[0] = (byte) 0x0;
// Set the source register for the first operand in the byte array
machineCode[1] = (byte) 0x0;
// Set the source register for the second operand in the byte array
machineCode[2] = (byte) 0x80;
// Set the destination register in the byte array
machineCode[3] = (byte) 0x21;
// Print the machine code
System.out.print("Machine Code: ");
for (byte b : machineCode) {
System.out.printf("%02X ", b);
}
System.out.println(); // Print newline
}
}
public class Nahi {
public static void main(String[] args) {
// Create a byte array to store the machine code
byte[] machineCode = new byte[6];
// Set the opcode for the MIPS instruction in the byte array
machineCode[0] = (byte) 0x2b;
// Set the source register in the byte array
machineCode[1] = (byte) 0x04;
// Set the base register in the byte array
machineCode[2] = (byte) 0x00;
// Set the offset in the byte array
machineCode[3] = (byte) 0x00;
machineCode[4] = (byte) 0x00;
machineCode[5] = (byte) 0x18;
// Print each byte of the machine code in hexadecimal format
for (byte code : machineCode) {
System.out.printf("%02X ", code);
}
}
}