+1 (208) 254-6996 [email protected]
  

1

Project 2

Don't use plagiarized sources. Get Your Custom Essay on
Like C N C++
Just from $13/Page
Order Essay

The second project involves completing and extending the C++ program that evaluates statements of an expression language contained in the module 3 case study.

The statements of that expression language consist of an arithmetic expression followed by a list of assignments. Assignments are separated from the expression and each other by commas. A semicolon terminates the expression. The arithmetic expressions are fully parenthesized infix expressions containing integer literals and variables. The valid arithmetic operators are +, –, *, /. Tokens can be separated by any number of spaces. Variable names begin with an alphabetic character, followed by any number of alphanumeric characters. Variable names are case sensitive. This syntax is described by BNF and regular expressions in the case study.

The program reads in the arithmetic expression and encodes the expression as a binary tree. After the expression has been read in, the variable assignments are read in and the variables and their values of the variables are placed into the symbol table. Finally the expression is evaluated recursively.

Your first task is to complete the program provided by providing the three missing classes, Minus, Times and Divide.

Next, you should extend the program so that it supports relational, logical and conditional expression operators as defined by the following extension to the grammar:

<exp> -> ‘(‘ <operand> <op> <operand> ‘)’ | ‘(‘ <operand> ‘:’ <operand> ‘?’ <operand> ‘)’ | ‘(‘ <operand> ‘!’ ‘)’ <op> -> ‘+’ | ‘-‘ | ‘*’ | ‘/’ | ‘>’ | ‘<‘ | ‘=’ | ‘&’ | ‘|’

Note that there are a few differences in the use of these operators compared to their customary use in the C family of languages. Their differences are:

 In the conditional expression operator, the symbols are reversed and the third operand represents the condition. The first operand is the value when true and the second the value when false

 The logical operators use single symbols not double, for example the and operator is & not &&  The negation operator ! is a postfix operator, not a prefix one  There are only three relational operators not the usual six and the operator for equality

is = not ==

Like C and C++, any arithmetic expression can be interpreted as a logical value, taking 0 as false and anything else as true

Your final task is to make the following two modifications to the program:

 The program should accept input from a file, allowing for multiple expressions arranged one per line.

2

 All results should be changed from double to int. In particular the evaluate function should return an int.

You may assume that all input to the program is syntactically correct.

Deliverables:

Deliverables for this project include the following:

1. Source code correctly implementing all required functionality. Your program must compile with Microsoft Visual C++ or any modern C/C++ compiler on your O/S.

2. Word or PDF file providing screen shots of successfully compiling and executing the program. 3. Description of the process and lesson learned while completing this project (to be included in

the Word or PDF document). 4. A test plan that contains test cases that test all of the required operators. Each test case should

include the expression and its expected value (to be included in the Word or PDF document).

Grading rubric:

Attribute Meets Does not meet

Functionality 40 points Completes the program provided in Module 3 by providing the three missing Classes: Minus, Times and Divide.

0 points Does not complete the program provided in Module 3 by providing the three missing Classes: Minus, Times and Divide.

Extends Functionality 20 points Extends the program so that it supports relational, logical and conditional expression operators.

All results should be changed from double to int. In particular the evaluate function should return an int.

0 points Does not extend the program so that it supports relational, logical and conditional expression operators. All results should be changed from double to int. In particular the evaluate function should return an int.

Input 20 points Accepts input from a file, allowing for multiple expressions arranged one per line.

0 points Does not accept input from a file, allowing for multiple expressions arranged one per line.

Documentation and submissions

20 points Includes source code correctly implementing all required functionality.

0 points Does not Include source code correctly implementing all required functionality.

3

Program compiles with Microsoft Visual C++ or any modern C/C++ compiler on your O/S.

Includes Word or PDF file providing screen shots of successfully compiling and executing the program.

Includes a description of the process and lesson learned while completing this project (to be included in the Word or PDF document).

Includes a test plan that contains test cases that test all of the required operators. Each test case should include the expression and its expected value (to be included in the Word or PDF document).

Program does not compile with Microsoft Visual C++ or any modern C/C++ compiler on your O/S.

Does not include Word or PDF file providing screen shots of successfully compiling and executing the program.

Does not include a description of the process and lesson learned while completing this project (to be included in the Word or PDF document).

Does not include a test plan that contains test cases that test all of the required operators. Each test case should include the expression and its expected value (to be included in the Word or PDF document)

1

Project 1

The first programming project involves writing a program that parses, using recursive descent, a GUI definition language defined in an input file and generates the GUI that it defines. The grammar for this language is defined below:

gui ::= Window STRING ‘(‘ NUMBER ‘,’ NUMBER ‘)’ layout widgets End ‘.’ layout ::= Layout layout_type ‘:’ layout_type ::= Flow | Grid ‘(‘ NUMBER ‘,’ NUMBER [‘,’ NUMBER ‘,’ NUMBER] ‘)’ widgets ::= widget widgets | widget widget ::= Button STRING ‘;’ | Group radio_buttons End ‘;’ | Label STRING ‘;’ | Panel layout widgets End ‘;’ | Textfield NUMBER ‘;’ radio_buttons ::= radio_button radio_buttons | radio_button radio_button ::= Radio STRING ‘;’

In the above grammar, the red symbols are nonterminals, the blue symbols are tokens and the black punctuation symbols are BNF metasymbols. Among the tokens those in title case are keywords. The character literals are punctuation tokens.

Below is an explanation of the meaning of some of the symbols in the above productions that should help you understand the actions that are to be performed when each of the productions is parsed:

 In the window production the string is the name that is to appear in the top border of the window and the two numbers are the width and height of the window

 In the production for layout_type that define the grid layout, the first two numbers represent the number of rows and columns, and the optional next two the horizontal and vertical gaps

 In the production for widget that defines a button, the string is the name of the button  In the production for widget that defines a label, the string is text that is to be placed in the label  In the production for widget that defines a text field, the number is the width of the text field  In the production for radio_button, the string is the label of the button

You parser should properly handle the fact that panels can be nested in other panels. Recursive productions must be implemented using recursion. Syntactically incorrect input files should detect and report the first error.

2

Below is an example of an input file:

Window “Calculator” (200, 200) Layout Flow: Textfield 20; Panel Layout Grid(4, 3, 5, 5): Button “7”; Button “8”; Button “9”; Button “4”; Button “5”; Button “6”; Button “1”; Button “2”; Button “3”; Label “”; Button “0”; End; End.

The above input file should produce the GUI shown below:

Deliverables:

Deliverables for this project include the following:

1. Source code correctly implementing all required functionality. 2. Word or PDF file providing screen shots of successfully compiling and executing the program. 3. Description of the process and lesson learned while completing this project (to be included in

the Word or PDF document). 4. A test plan that contains test cases that include both layout types, all widgets and nested panels.

For each test case, the input file should be shown together with the resulting GUI. (to be included in the Word or PDF document).

3

Grading rubric:

Attribute Meets Does not meet

Functionality 40 points Writes a program that parses an input file defining a GUI definition language using recursive descent. Properly handles the fact that panels can be nested in other panels. Implements recursive productions using recursion.

0 points Does not writes a program that parses an input file defining a GUI definition language using recursive descent. Does not properly handle the fact that panels can be nested in other panels. Does not implement recursive productions using recursion.

Input 20 points Syntactically incorrect input files should detect and report the first error.

0 points Syntactically incorrect input files do not detect and report the first error.

Output 20 points Generates the GUI that the input file defines.

0 points Does not generate the GUI that the input file defines.

Documentation and submissions

20 points Includes source code correctly implementing all required functionality.

Includes Word or PDF file providing screen shots of successfully compiling and executing the program.

Includes a description of the process and lesson learned while completing this project (to be included in the Word or PDF document).

0 points Does not Include source code correctly implementing all required functionality.

Does not include Word or PDF file providing screen shots of successfully compiling and executing the program.

Does not include a description of the process and lesson learned while completing this project (to be included in the Word or PDF document).

4

Includes a test plan that contains test cases that include both layout types, all widgets and nested panels. For each test case, the input file should be shown together with the resulting GUI. (to be included in the Word or PDF document).

Does not include a test plan that contains test cases that include both layout types, all widgets and nested panels. For each test case, the input file should be shown together with the resulting GUI. (to be included in the Word or PDF document).

import java.awt.Component; import java.awt.FlowLayout; import java.awt.GridLayout; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; import java.util.*; import java.lang.*; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class GUICreator { private static Scanner scnr; private static File inp_file; private static String getLabel(String file_lines) { int cntr; file_lines.trim(); for (cntr = 0; cntr < file_lines.length(); cntr++) { char tmp=file_lines.charAt(cntr); boolean b2 = Character.isLetter(tmp); if (!b2) { break; } } return file_lines.substring(0, cntr); } public static void main(String[] args) { String strng, lbl; try { inp_file = new File(“Input.txt”); scnr = new Scanner(inp_file); if (scnr.hasNextLine()) { strng = scnr.nextLine().trim(); lbl = getLabel(strng); if (!lbl.equalsIgnoreCase(“Window”)) { System.out.println(“First label should be WINDOW”); return; } strng = strng.substring(lbl.length()).trim(); JFrame frame = (JFrame) addCompntRec(strng, lbl); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } else { System.out.println(“Unknown Error”); } } catch (FileNotFoundException exp) { System.out.println(“File not found”); exp.printStackTrace(); } catch (Exception excep) { System.out.println(“Unknown Error”); excep.printStackTrace(); } } private static ArrayList<Integer> getIntAray(String strng) throws Exception { int lp, lpj; ArrayList<Integer> result = new ArrayList<Integer>(); for (lp = 0; lp < strng.length(); lp++) { for (lpj = lp; lpj < strng.length() && Character.isDigit(strng.charAt(lpj)); lpj++) ; if (lp != lpj) { result.add(Integer.parseInt(strng.substring(lp, lpj))); } lp = lpj; } return result; } private static Component addCompntRec(String strng, String lbl) throws Exception { String tempr; if (lbl.equalsIgnoreCase(“Window”)) { strng = strng.trim(); JFrame frame; if (strng.charAt(0) == ‘”‘) { strng = strng.substring(1); tempr = strng.substring(0, strng.indexOf(‘\”‘)); frame = new JFrame(tempr); strng = strng.substring(strng.indexOf(‘”‘) + 1).trim(); } else { frame = new JFrame(“Default title”); } if (strng.charAt(0) == ‘(‘) { tempr = strng.substring(0, strng.indexOf(‘)’) + 1); strng = strng.substring(tempr.length()).trim(); ArrayList<Integer> instr = getIntAray(tempr); if (instr.size() == 2) { frame.setSize(instr.get(0), instr.get(1)); } } tempr = getLabel(strng); strng = strng.substring(tempr.length()).trim(); JPanel lpnl = new JPanel(); if (tempr.equalsIgnoreCase(“Layout”)) { tempr = getLabel(strng); strng = strng.substring(tempr.length()).trim(); if (tempr.equalsIgnoreCase(“flow”)) { FlowLayout flw = new FlowLayout(); lpnl.setLayout(flw); } if (tempr.equalsIgnoreCase(“grid”)) { if (strng.charAt(0) == ‘(‘) { tempr = strng.substring(0, strng.indexOf(‘)’) + 1); strng = strng.substring(tempr.length()).trim(); ArrayList<Integer> instr = getIntAray(tempr); GridLayout tmpLayout; if (instr.size() == 2) { tmpLayout = new GridLayout(instr.get(0), instr.get(1)); lpnl.setLayout(tmpLayout); } else if (instr.size() == 4) { tmpLayout = new GridLayout(instr.get(0), instr.get(1), instr.get(2), instr.get(3)); lpnl.setLayout(tmpLayout); } } } } while (true) { if (scnr.hasNextLine()) { strng = scnr.nextLine().trim(); tempr = getLabel(strng); if (tempr.equalsIgnoreCase(“end”)) { break; } else { Component tmpCompnt = addCompntRec( strng.substring(tempr.length()), tempr); if (tmpCompnt != null) { if (tmpCompnt.getClass() == frame.getClass()) { System.out.println(“Window cant be nested inside”); } else { lpnl.add(tmpCompnt); } } } } else { System.out.println(“Error in nesting”); break; } } frame.add(lpnl); return frame; } if (lbl.equalsIgnoreCase(“panel”)) { strng = strng.trim(); JPanel pnel = new JPanel(); tempr = getLabel(strng); strng = strng.substring(tempr.length()).trim(); if (tempr.equalsIgnoreCase(“Layout”)) { tempr = getLabel(strng); strng = strng.substring(tempr.length()).trim(); if (tempr.equalsIgnoreCase(“flow”)) { FlowLayout flw = new FlowLayout(); pnel.setLayout(flw); } if (tempr.equalsIgnoreCase(“grid”)) { if (strng.charAt(0) == ‘(‘) { tempr = strng.substring(0, strng.indexOf(‘)’) + 1); strng = strng.substring(tempr.length()).trim(); ArrayList<Integer> instr = getIntAray(tempr); GridLayout tmpLayout; if (instr.size() == 2) { tmpLayout = new GridLayout(instr.get(0), instr.get(1)); pnel.setLayout(tmpLayout); } else if (instr.size() == 4) { tmpLayout = new GridLayout(instr.get(0), instr.get(1), instr.get(2), instr.get(3)); pnel.setLayout(tmpLayout); } } } } while (true) { if (scnr.hasNextLine()) { strng = scnr.nextLine().trim(); tempr = getLabel(strng); if (tempr.equalsIgnoreCase(“end”)) { break; } else { Component tmpCompnt = addCompntRec( strng.substring(tempr.length()), tempr); if (tmpCompnt != null) { if (tmpCompnt.getClass() == new JFrame() .getClass()) { System.out .println(“Window cant be nested inside”); } else { pnel.add(tmpCompnt); } } } } else { System.out.println(“Error in nesting”); break; } } return pnel; } if (lbl.equalsIgnoreCase(“button”)) { strng = strng.trim(); JButton button; if (strng.charAt(0) == ‘”‘) { strng = strng.substring(1); tempr = strng.substring(0, strng.indexOf(‘\”‘)); button = new JButton(tempr); strng = strng.substring(strng.indexOf(‘”‘) + 1).trim(); } else { button = new JButton(“Default title”); } return button; } if (lbl.equalsIgnoreCase(“lbl”)) { strng = strng.trim(); JLabel Label; if (strng.charAt(0) == ‘”‘) { strng = strng.substring(1); tempr = strng.substring(0, strng.indexOf(‘\”‘)); Label = new JLabel(tempr); strng = strng.substring(strng.indexOf(‘”‘) + 1).trim(); } else { Label = new JLabel(“Default title”); } return Label; } if (lbl.equalsIgnoreCase(“textfield”)) { strng =strng.trim(); ArrayList< Integer> li = getIntAray(strng); JTextField field = new JTextField(li.get(0)); return field; } return null; } }

Window “Calculator” (200, 200) Layout Flow: Textfield 20; Panel Layout Grid(4, 3, 5, 5): Button “7”; Button “8”; Button “9”; Button “4”; Button “5”; Button “6”; Button “1”; Button “2”; Button “3”; Label “”; Button “0”; End; End.

An Expression Interpreter

Module 3: Impera!ve Languages—Control Flow

An Expression Interpreter

The case study for this module incorporates two of

the language features that we discussed—

expressions and assignments. The program

interprets fully parenthesized arithme!c

expressions that contain either literal values or

variables. The variables must then subsequently be

assigned values.

The grammar for the language that this interpreter

accepts is defined by the following grammar:

<program> → <exp> , <assigns> ; <exp> → ( <operand> <op> <operand> ) <operand> → <literal> | <variable> | <exp> <assigns> → <assigns> , <assign> | <assign> <assign> → <variable> = <literal> The regular expressions defining the three tokens

are the following:

<op> [+-*/] <variable> [a-zA-Z][a-zA-Z0-9]* <literal> [0-9]+ So, if you were to enter the following expression:

(x + (y * 3)), x = 2, y = 6; the interpreter would respond:

Value = 20 The interpreter itself is wri”en in C++. The

complete program consists of 10 classes. We will

present 7 of them. Your instructor may ask you to

complete this program, perhaps enhance it, and add

some error checking as one of the programming

projects.

We begin with the main func!on and one

subordinate func!on, which are contained in

module3.cpp. The main func!on reads in the

program, calls upon the sta!c func!on parse of the

SubExpression class to parse it, and builds an

arithme!c expression tree. It then calls the

subordinate func!on parseAssignments to parse

the assignments and enter them into the symbol

table, and then evaluates the expression and

displays the result. That code is shown below:

#include <iostream> #include <string> #include <vector> using namespace std;

#include “expression.h” #include “subexpression.h” #include “symboltable.h”

#include “parse.h”

SymbolTable symbolTable;

void parseAssignments();

int main() { Expression* expression; char paren, comma; cout << “Enter expression: “; cin >> paren; expression = SubExpression::parse(); cin >> comma; parseAssignments(); cout << “Value = ” << expression->evaluate() << endl; return 0; }

void parseAssignments() {

char assignop, delimiter; string variable; double value; do { variable = parseName(); cin >> ws >> assignop >> value >> delimiter; symbolTable.insert(variable, value); } while (delimiter == ‘,’); } The arithme!c expression tree is built using an

inheritance hierarchy. At the root of the hierarchy

is the abstract class Expression. The class defini!on

for Expression is contained in the file expression.h,

shown below:

class Expression { public:

virtual double evaluate() = 0; }; This abstract class has two subclasses. The first of

these is SubExpression, which defines the node of

the binary arithme!c expression tree. The class

defini!on for SubExpression is contained in the file

subexpression.h, shown below:

class SubExpression: public Expression { public: SubExpression(Expression* left, Expression* right); static Expression* parse(); protected: Expression* left; Expression* right; }; As is customary in C++, the bodies of the member

func!ons of that class are contained in the file

subexpression.cpp, shown below:

#include <iostream>

using namespace std;

#include “expression.h” #include “subexpression.h” #include “operand.h” #include “plus.h” #include “minus.h” #include “times.h” #include “divide.h”

SubExpression::SubExpression(Expres sion* left, Expression* right) { this->left = left; this->right = right; }

Expression* SubExpression::parse() { Expression* left; Expression* right; char operation, paren;

left = Operand::parse(); cin >> operation; right = Operand::parse(); cin >> paren; switch (operation) { case ‘+’: return new Plus(left, right); case ‘-‘: return new Minus(left, right); case ‘*’: return new Times(left, right); case ‘/’: return new Divide(left, right); } return 0; } The SubExpression class has four subclasses. We

show one of them—Plus. The class defini!on for

Plus is contained in the file plus.h, shown below:

class Plus: public SubExpression { public: Plus(Expression* left, Expression* right): SubExpression(left, right) { } double evaluate() { return left->evaluate() + right->evaluate(); } }; Because the bodies of both member func!ons are

inline, no corresponding .cpp file is required.

The other subclass of Expression is Operand, which

defines the leaf nodes of the arithme!c expression

tree. The class defini!on for Operand is contained

in the file operand.h, shown below:

class Operand: public Expression { public: static Expression* parse(); }; The body of its only member func!on is contained

in operand.cpp, shown below:

#include <cctype> #include <iostream> #include <list> #include <string>

using namespace std;

#include “expression.h” #include “subexpression.h” #include “operand.h” #include “variable.h” #include “literal.h” #include “parse.h”

Expression* Operand::parse()

{ char paren; double value;

cin >> ws; if (isdigit(cin.peek())) { cin >> value; Expression* literal = new Literal(value); return literal; } if (cin.peek() == ‘(‘) { cin >> paren; return SubExpression::parse(); } else return new Variable(parseName()); return 0; }

The Operand class has two subclasses. The first is

Variable, which defines leaf nodes of the tree that

contain variables. The class defini!on for Variable is

contained in the file variable.h, shown below:

class Variable: public Operand { public: Variable(string name) { this->name = name; } double Variable::evaluate(); private: string name; }; The body of its member func!on evaluate is

contained in variable.cpp, shown below:

#include <strstream> #include <vector> using namespace std;

#include “expression.h”

#include “operand.h” #include “variable.h” #include “symboltable.h”

extern SymbolTable symbolTable;

double Variable::evaluate() { return symbolTable.lookUp(name); } The other subclass of Operand is Literal, which

defines leaf nodes of the tree that contain literal

values. The class defini!on for Literal is contained

in the file literal.h, shown below:

class Literal: public Operand { public: Literal(int value) { this->value = value; }

double evaluate() { return value; } private: int value; }; This interpreter uses a symbol table that is

implemented with an unsorted list defined by the

class SymbolTable. Its class defini!on is contained

in the file symboltable.h, shown below:

class SymbolTable { public: SymbolTable() {} void insert(string variable, double value); double lookUp(string variable) const; private: struct Symbol {

Symbol(string variable, double value) { this->variable = variable; this->value = value; } string variable; double value; }; vector <Symbol> elements; }; The bodies of its member func!ons are in the file

symboltable.cpp, shown below:

#include <string> #include <vector> using namespace std;

#include “symboltable.h”

void SymbolTable::insert(string

variable, double value) { const Symbol& symbol = Symbol(variable, value); elements.push_back(symbol); }

double SymbolTable::lookUp(string variable) const { for (int i = 0; i < elements.size(); i++) if (elements[i].variable == variable) return elements[i].value; return -1; } Finally, one u!lity func!on, parseName, is needed

by this program. Its func!on prototype is the file

parse.h, shown below:

string parseName();

Its body is in parse.cpp, shown below:

#include <cctype> #include <iostream> #include <string> using namespace std;

#include “parse.h”

string parseName() { char alnum; string name = “”;

cin >> ws; while (isalnum(cin.peek())) { cin >> alnum; name += alnum; } return name; }

Order your essay today and save 10% with the discount code ESSAYHELP