Professional Documents
Culture Documents
CD Assessment 4
CD Assessment 4
CD Assessment 4
Table of Contents
[Question 1]
Page 2 of 9
Name: Surjosnath Guha Thakurta
Registration No.: 21BDS0177
Aim:
Generate Three address code for the following statement
Eg. a = (-c * b) + (-c * d)
Ans:
t₁ = -c
t₂ = b*t₁
t₃ = -c
t₄ = d * t₃
t₅ = t₂ + t₄
a = t₅
Code:
#include <iostream>
#include <string>
#include <stack>
Page 3 of 9
Name: Surjosnath Guha Thakurta
Registration No.: 21BDS0177
code += temp + " = " + op1 + " " + op + " " + op2 + "\n";
}
operators.pop();
}
else if (isOperator(ch))
{
while (!operators.empty() && operators.top() != '(' &&
getPrecedence(operators.top()) >= getPrecedence(ch))
{
string op2 = operands.top();
operands.pop();
string op1 = operands.top();
operands.pop();
char op = operators.top();
operators.pop();
code += temp + " = " + op1 + " " + op + " " + op2 + "\n";
Page 4 of 9
Name: Surjosnath Guha Thakurta
Registration No.: 21BDS0177
}
operators.push(ch);
}
}
while (!operators.empty())
{
string op2 = operands.top();
operands.pop();
string op1 = operands.top();
operands.pop();
char op = operators.top();
operators.pop();
code += temp + " = " + op1 + " " + op + " " + op2 + "\n";
}
return code;
}
int main()
{
string expression;
cout << "Enter an assignment statement: ";
getline(cin, expression);
return 0;
}
Output:
Page 5 of 9
Name: Surjosnath Guha Thakurta
Registration No.: 21BDS0177
[Question 2]
Page 6 of 9
Name: Surjosnath Guha Thakurta
Registration No.: 21BDS0177
Aim:
Generate the three address codes for the following:
for(i = 1; i<=10; i++)
{ a[i]=x * 5; }
Ans:
i=1
L:t1=x*5
t2=&a
t3=sizeof(int)
t4=t3*i
t5=t2+t4
*t5=t1
i=i+1
if i<10 goto L
Code:
#include <iostream>
#include <string>
#include <vector>
// Initialize variables
threeAddressCode.emplace_back("i=1");
// Loop start
threeAddressCode.emplace_back("L:");
currentCode = "t1=x*5";
threeAddressCode.emplace_back(currentCode);
currentCode = "t2=&a";
threeAddressCode.emplace_back(currentCode);
currentCode = "t3=sizeof(int)";
threeAddressCode.emplace_back(currentCode);
currentCode = "t4=t3*i";
threeAddressCode.emplace_back(currentCode);
currentCode = "t5=t2+t4";
Page 7 of 9
Name: Surjosnath Guha Thakurta
Registration No.: 21BDS0177
threeAddressCode.emplace_back(currentCode);
currentCode = "*t5=t1";
threeAddressCode.emplace_back(currentCode);
currentCode = "i=i+1";
threeAddressCode.emplace_back(currentCode);
// Loop condition
currentCode = "if i<10 goto L";
threeAddressCode.emplace_back(currentCode);
return threeAddressCode;
}
int main()
{
std::string userInput;
std::cout << "Enter the code: ";
std::getline(std::cin, userInput);
std::vector<std::string> threeAddressCode =
generateThreeAddressCode(userInput);
return 0;
}
Output:
Page 8 of 9
Name: Surjosnath Guha Thakurta
Registration No.: 21BDS0177
Page 9 of 9