Interpreter:
- Interpreter executes each statement of a program at a time.
- It calls recursive functions for “statement”, “expression”, “factor”, “term” and “Identifier” to execute a statement.
- It allows arithmetic operations such as addition, subtraction, multiplication and division.
/**********************************************************
* This program extends the interpreter with integer *
* division. *
**********************************************************/
Explanation of Solution
//interpreter.h
//Include header files
#ifndef INTERPRETER
#define INTERPRETER
#include <iostream>
#include <list>
#include <algorithm> // find
using namespace std;
//Definition of class IdNode
class IdNode
{
//Declare public methods
public:
//Declare Parameterized constructor
IdNode(char *s = "", double e = 0)
{
//Initialize variables
id = strdup(s);
value = e;
}
//Function to overload operator ==
bool operator== (const IdNode& node) const
{
/*Return true if both string are same, otherwise return false*/
return strcmp(id,node.id)==0;
}
//Declare private variables and overloading function
private:
//Declare variables
char *id;
double value;
//Declare class object
friend class Statement;
//Prototype for overloading function
friend ostream& operator<<(ostream&, const IdNode&);
};
//Definition of class Statement
class Statement
{
//Declare public functions
public :
//Constructor
Statement(){}
//Declare function getStatement()
void getStatement();
//Declare private variables
private:
//Declare variables
list<IdNode>idList;
char ch;
//Function prototypes
double factor();
double term();
double expression();
int fl1,fl2,fl3;
void readId(char*);
//Declare function to print error message
void issueError(char* s)
{
cerr << s << endl; exit(1);
}
//Function prototypes
double findValue(char*);
void processNode(char*, double);
friend ostream& operator<< (ostream&, const Statement&);
};
#endif
//interpreter.cpp
//Include header files
#include <cctype>
#include <stdio.h>
#include <string.h>
#include <string>
#include <list>
#include "interpreter.h"
//Function to find value of identifier
double Statement::findValue(char *id)
{
//Create object of class IdNode for id
IdNode tmp(id);
/*If identifier is present in IdNode list, return position */
list<IdNode>::iterator i = find(idList.begin(),idList.end(),tmp);
//If position is not end of list
if (i != idList.end())
//Return value of identifier
return i->value;
//Otherwise
else
//Print error message
issueError("Unknown variable");
// This statement will never be reached;
return 0;
}
//Function to process node
void Statement::processNode(char* id,double e)
{
/*Create object of class for IdNode for statement*/
IdNode tmp(id,e);
/*If identifier is present in IdNode list find position of identifier*/
list<IdNode>::iterator i = find(idList.begin(),idList.end(),tmp);
//If position of identifier is not end of IdNode list
if (i != idList.end())
//Set value of identifier as value of expression
i->value = e;
//Otherwise
else
//Insert New value into list
idList.push_front(tmp);
}
/* readId() reads strings of letters and digits that start with a letter, and stores them in array passed to it as an actual parameter.*/
/* Examples of identifiers are: var1, x, pqr123xyz, aName, etc.*/
//Function to read identifier
void Statement::readId(char *id)
{
//Initialize variable i as 0
int i = 0;
//If ch is space
if (isspace(ch))
//Skip balks and read next character
cin >> ch;
//If character is alphabet
if (isalpha(ch))
{
//Read character till read a non-alphanumeric
while (isalnum(ch))
{
//Copy each character to identifier
id[i++] = ch;
//Read next character
cin.get(ch);
}
//Set last character as end of string
id[i] = '\0';
}
//Otherwise
else
//Print error message
issueError("Identifier expected");
}
//Function factor()
double Statement::factor()
{
//Declare variables
double var, minus = 1.0;
static char id[200];
fl3=0;
//Read character
cin >> ch;
//If ch is operator + or -
while (ch == '+' || ch == '-')
{
// take all '+'s and '-'s.
//If ch is -
if (ch == '-')
/*Set value as negative by multiplying with -1*/
minus *= -1.0;
//Read next character
cin >> ch;
}
//If ch is digit or operator dot
if (isdigit(ch) || ch == '.')
{
// Factor can be a number
//Read digits of number
cin.putback(ch);
//Append digits to variable to form number
cin >> var >> ch;
}
//If ch is paranthesis (
else if (ch == '(')
{
//Get next expression after (
var = expression();
//If character is )
if (ch == ')')
//Read next character
cin >> ch;
//Otherwise
else
//Print error message
issueError("Right paren left out");
}
//Otherwise
else
{
//Read identifier
readId(id);
//If chracter is space
if (isspace(ch))
//Read next character
cin >> ch;
//Get value of identifier
var = findValue(id);
}
//If value of var is an integer
if (var-(int)var == 0)
{
//Set flag fl3 as 1
fl3=1;
}
//Return value
return minus * var;
}
//Function for term()
double Statement::term()
{
//Call function factor()
double f= factor();
//Do calculation for operators * and /
while (true)
{
//Switch statement
switch (ch)
{
//If ch is *, multiply recursively
case '*' : f *= factor(); break;
//If ch is /
case '/' :
//If fl3 equals 1
if (fl3 == 1)
{
//Set fl1 as 1
fl1=1;
}
//If fl3 equals 0
else
//Set fl1 as 0
fl1=0;
//Divide recursively
f /= factor();
//If fl3 equals 1
if (fl3 == 1)
{
//Set fl2 as 1
fl2=1;
}
//If fl3 equals 0
else
//Set fl2 as 0
fl2=0;
//If both fl1 and fl2 are 1
if(fl1==1 && fl2==1)
{
//Take integer part as result
f=(double)((int)f);
}
//Otherwise
else
{
/*Take double value itself as result*/
f=f;
}
break;
//Default
default:
//Return result
return f;
}
}
}
//Function for expression()
double Statement::expression()
{
//Call function term()
double t = term();
//Do calculation for operators + and -
while (true)
{
//Switch statement
switch (ch)
{
//If ch is +, adds numbers recursively
case '+' : t += term(); break;
//If ch is -, subtract numbers recursively
case '-' : t -= term(); break;
// Return f
default : return t;
}
}
}
//Function to read statement
void Statement::getStatement()
{
//Declare variables
char id[20], command[20];
double e;
//Prompt and read statement
cout << "Enter a statement: ";
cin >> ch;
//Read identifier
readId(id);
//Copy identifier to string command
strupr(strcpy(command,id));
//If command is STATUS
if (strcmp(command,"STATUS") == 0)
//Print current values of all variables
cout << *this;
//If command is PRINT
else if (strcmp(command,"PRINT") == 0)
{
//Read identifier from user
readId(id);
//Get value of identifier and print it
cout << id << " = " << findValue(id) << endl;
}
//If command is END
else if (strcmp(command,"END") == 0)
//Retun from program
exit(0);
//Otherwise
else
{
//If ch is space
if (isspace(ch))
//Read next character
cin >> ch;
//If ch is =
if (ch == '=')
{
//Read expression
e = expression();
//If ch is not ;
if (ch != ';')
//print error message
issueError("There are some extras in the statement");
//Otherwise process statement
else processNode(id,e);
}
//Otherwise print error message
else issueError("'=' is missing");
}
}
/*Function to overload operator << to print values all identifiers in list*/
ostream& operator<< (ostream& out, const Statement& s)
{
//Initialize iterator
list<IdNode>::const_iterator i = s.idList.begin();
//For each identifier
for ( ; i != s.idList.end(); i++)
//Print value of identifier
out << *i;
//Print new line
out << endl;
return out;
}
/*Function to overload operator << to print value of identifier*/
ostream& operator<< (ostream& out, const IdNode& r)
{
//Print value of identifier
out << r.id << " = " << r.value << endl;
return out;
}
//useInterpreter.cpp
//Include header files
#include "interpreter.h"
using namespace std;
//Program begins with main()
int main()
{
//Declare object of class Statement
Statement statement;
//Prompt message
cout << "The program processes statements of the following format:\n"<< "\t<id> = <expr>;\n\tprint <id>\n\tstatus\n\tend\n\n";
// This infinite loop is broken by exit(1)
while (true)
// in getStatement() or upon finding an
statement.getStatement();
//Return 0
return 0;
}
Explanation:
- Declare integer type flag variables “fla1”, “fla2” and “fla3” in class “Statement”.
- In function “factor()”,
- Initialize “fla3” as “0”,
- If number is integer type set “fla3” as “1”
- In Function “term()”
- If “ch” is “/” operator and “fla3” is “1”, set “fla1” as “1”.
- If “fla3” is “1” after recursive call of function “factor()” (That is after division), set “fla2” as “1”.
- If both flags “fla1” and “fla2” are “1” (That is both are integers for division), remove floating part of result.
Output:
The program processes statements of the following format:
<id> = <expr>;
print <id>
status
end
Enter a statement: var1=2+(11/2);
Enter a statement: var2=var1+(15.5/3.7);
Enter a statement: var3=var2*(8.2/2);
Enter a statement: status
var3 = 45.8757
var2 = 11.1892
var1 = 7
Enter a statement: var4=var3+(8/1.1);
Enter a statement: print var4
var4 = 53.1484
Enter a statement: end
Want to see more full solutions like this?
Chapter 5 Solutions
EBK DATA STRUCTURES AND ALGORITHMS IN C
- In C++, what is the benefit of using typedefs in a program? Here is an exmaple line of code: typedef double value_type; Does this mean that value_type therefore gets used throughout the program as a specified description for a double? Why can't we just use double always?arrow_forwardSmith is a course instructor of C++ programming and currently he is teaching conversions to his students. He started with the basic programs and now he wants to introduce some complex problems. Before starting the complex problems, he wants to start with a high difficulty level problem, such as: counting the digits of a number. Help Mr. Smith to write a program that will accept one integer argument and returns count of digits of that argument using class to class conversionarrow_forwardNote: I want to solve my problem with C programming. In no way can this be done with C ++ programming. Questioin: Hidden Secret Problem! In this problem, you are given two names, you have to find whether one name is hidden into another. The restrictions are: You can change some uppercase letters to lower case and vice versa. You can add/remove spaces freely. You can permute the letters. And if both the names match exactly, then you can say that one name is hidden into another. Input Input starts with an integer T (≤ 100), denoting the number of test cases. Each case starts with two lines. Each line contains a name consists of upper/lower case English letters and spaces. You can assume that the length of any name is between 1 and 100(inclusive). Output For each case, print the case number and Yes if one name is hidden into another. Otherwise print No. Sample Input Output 3 Tom Marvolo Riddle I am Lord Voldemort I am not Harry Potter Hi Pretty Roar to man…arrow_forward
- Write a program in C++ that reads HAND_SIZE cards from the user, then analyzes the cards and prints out the type of poker hand that they represent. (HAND_SIZE will be a global constant, typically 5, but your program must still work if it is set to something other than 5.) Poker hands are categorized according to the following hand-types: Straight flush, four of a kind, full house, straight, flush, three of a kind, two pairs, pair, high card. To simplify the program we will ignore card suits, and face cards. The values that the user inputs will be integer values from LOWEST_NUM to HIGHEST_NUM. (These will be global constants. We'll use LOWEST_NUM = 2 and HIGHEST_NUM = 9, but your program must work if these are set to something different.) When your program runs it should start by collecting HAND_SIZE integer values from the user and placing the integers into an array that has HAND_SIZE elements. It might look like this: Enter 5 numeric cards, no face cards. Use 2 - 9. Card 1: 8 Card 2:…arrow_forwardWrite a C++ program. Only use string, vector and iterator types from STL for solving these two problems. You can also use a math library. Q2: Design a game that mimics Wordle. Design the code by using functions as much as you can. You do not need to design a graphical interface as shown on the website. This assignment is about designing the underlying logic. Hardcode a set of valid dictionary words in your program. At the end of each try, you can output the text as shown in their example below (i.e., "The letter W is in the word and in the correct spot."): W EARY The letter W is in the word and in the correct spot. ILLS The letter I is in the word but in the wrong spot. V AGUE The letter U is not in the word in any spot.arrow_forwardWrite a program in C++ that uses only the "write" system call to print out a variable. Write a program in C++ that only uses the "write" system call to print out a integer literal. Write a program in C++ that only uses the "write" system call to print out a string literal. Write a program in C++ that only uses the "write" system call to print out an element of an array.arrow_forward
- We have covered conditional statements in python. Research what the keyword assert does and how you could using it within a loop or function. In addition to this, Switch statements are typically found in languages such as C++ and Java. They are used in place of using large if /elif /else structures. Research how an equivalent switch statement can be implemented in Python and give an example.arrow_forwardWrite a program in C or C++ that converts decimal numbers to binary, hexadecimal, and BCD. You are not allowed to use library functions to do conversion. The output should look as follows. Send the output to a file and upload it along with your source file. DECIMAL BINARY HEXDECIMAL BCD 0 0000 0000 00 0000 0000 0000 1 0000 0001 01 0000 0000 0001 2 0000 0010 02 0000 0000 0010 . . . . . . . . 255 1111 1111 FF 0010 0101 0101arrow_forwardI'm not sure how to implement the Coin::~Coin() function, i think we are supposed to do delete since it's a destructor because I keep getting error. I have provided the demo.cpp given to me. This is in C++, please explain to me as well thanks!arrow_forward
- Write a C program that uses arrays and functions to implement a calculator for twooperands. Your calculator must have five principal operations, addition ( ), subtraction ( ),division ( ), multiplication ( ), and power ( ). In the beginning of the program, show the menuof operators to the user. When the user selects one of the operators, your program gets the valuesfor operand 1 and operand 2 from the user and saves them into an array. Then pass the array to thesuitable function to calculate the result. The operating functions must return the value to the mainprogram. The calculation stops when the user press “x”. Use a global variable to save the result oflast operation. Anytime that the user types “M”, the program shows the result of last operation.hint: Each mathematic operation must be a separate function. Your main program calls those functions.arrow_forwardHelp writing a program in c++ that asks a user for a number (variable num) and then takes that number input to print out the nth term of a sequence? The sequence begins with 1 and then every number after is a prime factor of 3, 4, or 6. This needs to be done without using vectors or arrays. . . . For example: Sequence is : 1, 3, 4, 6, 8, 9, 12, 16, 18, 20, ... (cont.) User input (num) is : 6 Output : 12 (6th term) . . Please add comments explaining the code for better understanding if possible, thank you!!arrow_forwardWrite a console application in c++ that prints the next 20 leap years. A leap year is a year in which an extra day is added to the Gregorian calendar, which is used by most of the world. While an ordinary year has 365 days, a leap year has 366 days. ... A leap year comes once every four years. Because of this, a leap year can always be evenly divided by four.arrow_forward
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education