Question

For this assignment you will implement a simple calculator or interpreter that reads arithmetic expressions from...

For this assignment you will implement a simple calculator or interpreter that reads arithmetic expressions from a file.

Specifically, you will implement the following function:

/*

* Reads one arithmetic "expression" at a time from a file stream, computes, then

* returns the result. If there are additional expressions in the file, they are

* read and computed by successive calls to “calculator”.

*

* “Expressions” are groups of operations (add, subtract, multiply, divide). Your

* calculator will read and execute these operations one by one to compute the

* result of anexpression.

*

* Much like a standard calculator, your function will be able to use the result

* from the immediately previous computation.

*

* Here is a sample “add” (adds 5+4) operation, see the .h file or the later part

* of this specification for more information about the operation format.

*

* 0 5 4

*

* More than one operation can be grouped into a single

* "expression". Here is a sample file:

*

*    3

*    0 5 4

*    1 4

*    5 2

*

*    1

*    2 3 1

*

*    1

*    7 2

*

* In this example there are 3 expressions. Each expression is preceded by a

* single number telling you how many operations there are in an expression. So

* the first expression has 3 operations (the first one is the add operation from

* above).

*

* The next expression has one operation and the last expression also has a

* single operation.

*

*

* Pre: calc_cmd is has been initialized with a file opened in

* read mode.

*

* Post: The result of the next “expression” in the file is returned. So the first

* call to calculator with above file would return ((4 + 5) + 4) * 2 = 26, the

* second (3-1) = 2, and the third (0 / 2) = 0. If there are no more expressions

* or an error is encountered -1 is returned.

*

*/

int calculator(FILE* calc_cmd);

(C code, Linux)

GIVEN:

calculator.c : (This is what needs to be changed

#include "calculator.h"

int calculator(FILE* calc_cmd)
{


        return -1;
}

calculator.h:

#ifndef CALCULATOR_H_
#define CALCULATOR_H_

#include 
int calculator(FILE* calc_cmd);


#endif

driver.c :

#include        // for I/O functions
#include       // for C99 exact-width integer types
#include     // for formatting of stdint types
#include         // for time(); used for random number generator
#include       // for rand() and srand()

#include "calculator.h"

/* Test driver for the simple calculator program */
int main(int argc, char ** argv)
{
        /* check the number of parameters, here in the program we expect 2 
         * (1) the program name, i.e. "driver" 
         * (2) the filename
         * So, if we don't have exactly 2 we stop the program 
         */
        if(argc != 2)
        {
                printf("Error: Incorrect number of parameters.\n");
                printf("Usage: driver filename.txt\n");
                return 1;
        }


        /* open the file provided on the command line */
        FILE * calc_cmds = fopen(argv[1], "r");

        /* we need to test the file was opened properly, if the FILE*
         * is NULL then we have a problem 
         */
        if(calc_cmds == NULL)
        {
                printf("Error: Could not open file: %s.\n", argv[1]);
                return 2;

        }

        printf("Begin testing calculator function: \n");

        int output, count = 1;

        /* here we test your function */
        while((output = calculator(calc_cmds)) != -1)
        {

                printf("The result of equation %d is %d\n", count, output); 
                count++;
        }

        printf("End testing calculator function.\n");

        return 0;
}

test.txt:

3
0 5 4   
1 4
5 2 

1
2 3 1 

1
7 2

Extra Info:

The focus of the assignment is understanding C I/O functions like fscanf().

Program Logic: In this assignment, you will implement a simple calculator with addition, subtraction, multiplication, and division operations.Further, those operations can be combined together to create larger computations or “expressions”, so your calculator will be able to computethings like: ((5 + 4) + 4) * 2. All of the operations and expressions will be read from a file. Further, all of these operations will use will integers when performing calculations. Much like a standard calculator, your program will be able to use the result from the immediately previous computation. Only the last the result from the previous computation needs to be stored. For the remainder of the specification we refer to this as the "Previous Result". Initially, the Previous Result should be zero, also note that the value of the Previous Result is not retained across function calls. Calculator Operations Operations in the file have a type, which is represented by an integer, followed by either one or two parameters, which are also integers, depending on the type of the operation. Each operation is stored on a single line in the file, and looks like either:

<operation type (int)> <argument 1 (int) > < argument 2 (int)>

or

<operation type (int)> <argument1 (int)>

For example, "0 3 2" in the input file, is the "add" (represented by a 0) operation and it has two parameters. After this line is “executed”, the result 5 (3 + 2) is stored (this is now the Previous Result).

As another example, if the next line in file is “1 2”, it is the add operation that uses the Previous Result (5 in this case) and is the equivalent of 5 + 2. The standalone operations take 2 parameters while the operations that use the Previous Result take only 1 parameter.

Here are all of the operations your calculator must support, their format, parameters, and behavior:

Adding

0 X Y - same as X + Y, stores the newly computed result in Previous Result

1 Y - same as Previous Result + Y, stores the newly computed result in Previous Result

Subtracting

2 X Y - same as X - Y, stores the newly computed result in Previous Result

3 Y - same as Previous Result - Y, stores the newly computed result in Previous Result

Multiplying

4 X Y - same as X * Y, stores the newly computed result in Previous Result

5 Y - same as Previous Result * Y, stores the newly computed result in Previous Result

Dividing

6 X Y - same as X / Y, you don't have to worry about if Y is 0, stores the newly computed result in Previous Result

7 Y - same as Previous Result / Y, like above you don't have worry if Y is 0, stores the newly computed result in Previous Result

Note: that the order of the operations in the file, isthe order they should be computed in, so you can assume there are implied parentheses around each operation

Homework Answers

Answer #1

Hi,

As your problem suggests that you need to get the values from a file so you need to make a object of filestream as:

FileStreaam fs=new FileStream();

or you can create the object of inputstreamreader to do so.Also,as you need to check for the expressions in the file data but you have not mentioned the exact order of expression that you need but you can check that with the help of either if condition or switch case and you can store the result into some variable and after your calculation gets over , you can store this in to the file object that you created before.Like this , you can approach your problem.

I hope this solves your problem.Please let me know in case of any further queries.

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Consider the C program (twoupdate) to demonstrate race condition. In this assignment, we will implement Peterson's...
Consider the C program (twoupdate) to demonstrate race condition. In this assignment, we will implement Peterson's algorithm to ensure mutual exclusion in the respective critical sections of the two processes, and thereby eliminate the race condition. In order to implement Peterson's Algorithm, the two processes should share a boolean array calledflagwith two components and an integer variable called turn, all initialized suitably. We will create and access these shared variables using UNIX system calls relating to shared memory – shmget,...
Description: In this assignment, you need to implement a recursive descent parser in C++ for the...
Description: In this assignment, you need to implement a recursive descent parser in C++ for the following CFG: 1. exps --> exp | exp NEWLINE exps 2. exp --> term {addop term} 3. addop --> + | - 4. term --> factor {mulop factor} 5. mulop --> * | / 6. factor --> ( exp ) | INT The 1st production defines exps as an individual expression, or a sequence expressions separated by NEWLINE token. The 2nd production describes an...
CS4315 Operating Systems Lab 2: Linux Processes This lab assignment contains three questions. To submit this...
CS4315 Operating Systems Lab 2: Linux Processes This lab assignment contains three questions. To submit this lab assignment, please use a Word document to include the screenshots and write your answer. 1. Run the following C program, and submit a screenshot of the result. #include <sys/types.h> #include <stdio.h> #include <unistd.h> int main( ) { pid_t pid; if ( (pid = fork()) == 0 ) { printf (“I am the child, my pid = %d and my parent pid = %d\n”,...
PLEASE EXPLAIN THE ANSWER The file data1 contains: 0 3 6 9 12 The file data2...
PLEASE EXPLAIN THE ANSWER The file data1 contains: 0 3 6 9 12 The file data2 contains: 10 8 6 4 2 The file data3 contains: 20 10 0 20 80 Give the output when run with: ./a.out data1 data2 data3 #include <stdio.h> int main( int argc, char *argv[] ) { FILE *fpOne = fopen(argv[1], "r"); FILE *fpTwo = fopen(argv[2], "r"); FILE *fpThree = fopen(argv[3], "r"); int a, num1, num2, num3, sum1=0, sum2=0; for (a=0; a<5; a++) { fscanf(fpOne, "%d",...
#include <stdio.h> #pragma warning(disable : 4996) // CSE 240 Fall 2016 Homework 2 Question 3 (25...
#include <stdio.h> #pragma warning(disable : 4996) // CSE 240 Fall 2016 Homework 2 Question 3 (25 points) // Note: You may notice some warnings for variables when you compile in GCC, that is okay. #define macro_1(x) ((x > 0) ? x : 0) #define macro_2(a, b) (3*a - 3*b*b + 4*a * b - a*b * 10) int function_1(int a, int b) { return (3*a - 3*b*b + 4*a * b - a*b * 10); } // Part 1: //...
(For Python) Evaluating Postfix Arithmetic Expressions. In this project you are to implement a Postfix Expression...
(For Python) Evaluating Postfix Arithmetic Expressions. In this project you are to implement a Postfix Expression Evaluator as described in section 7-3b of the book. The program should ask the user for a string that contains a Postfix Expression. It should then use the string's split function to create a list with each token in the expression stored as items in the list. Now, using either the stack classes from 7.2 or using the simulated stack functionality available in a...
#include <stdio.h> #pragma warning(disable : 4996) // needed in VS // CSE 240 Fall 2019 Homework...
#include <stdio.h> #pragma warning(disable : 4996) // needed in VS // CSE 240 Fall 2019 Homework 2 Question 3 (25 points) // Note: You may notice some warnings when you compile in GCC or VS, that is okay. #define isNegative(x) ((x < 0) ? x : 0) #define polyMacro(a, b) (a*a + 8*a + 3*a*b - b*b) int polyFunc(int a, int b) { return (a*a + 8*a + 3*a*b - b*b); } // Part 1: // We want to pass...
Convert the following C program to C++. More instructions follow the code. #include <stdio.h> #include <stdlib.h>...
Convert the following C program to C++. More instructions follow the code. #include <stdio.h> #include <stdlib.h> #define SIZE 5 int main(int argc, char *argv[]) {    int numerator = 25;    int denominator = 10;    int i = 0;    /*    You can assume the files opened correctly and the    correct number of of command-line arguments were    entered.    */    FILE * inPut = fopen(argv[1], "r");    FILE * outPut = fopen(argv[2], "w");    float result =...
PLEASE EXPLAIN EACH LINE OF CODE ONLY. USE COMMENTS NEXT TO EACH LINE TO EXPLAIN WHAT...
PLEASE EXPLAIN EACH LINE OF CODE ONLY. USE COMMENTS NEXT TO EACH LINE TO EXPLAIN WHAT EACH IS CODE IS DOING THANKS. PLEASE COPY PASTE AFTER YOURE DONE NOT SCREENSHOT BECAUSE I NEED TO BE ABLE TO EDIT IT THANKS. // MODULE B: Method 2: Embedding an in-line asssembly language module in a C progrmming #include "stdafx.h" #include "stdio.h" #include<iostream> int main () { printf(" Lab_No_01_Getting_Stated_into_x86_Assembly_from_a_C++_program\n"); // Lab number and title here printf(" Module B: Embedding an in-line asssembly language...
This is C programming assignment. The objective of this homework is to give you practice using...
This is C programming assignment. The objective of this homework is to give you practice using make files to compose an executable file from a set of source files and adding additional functions to an existing set of code. This assignment will give you an appreciation for the ease with which well designed software can be extended. For this assignment, you will use both the static and dynamic assignment versions of the matrix software. Using each version, do the following:...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT
Active Questions
  • Nursing Care of Patient with Peptic Ulcer Disease Abstract: Cedric Filmore, age 40, is transferred to...
    asked 3 minutes ago
  • describe the three fiscal policy tools at the government's disposal to stimulate or contract the economy....
    asked 26 minutes ago
  • i) Write the condensed electron configurations for the following ions: (a) Ca+ (b) S2- (c) V2+...
    asked 26 minutes ago
  • In Java a function can call itself(we may explore more about this later in the course).  This...
    asked 39 minutes ago
  • Write a short program,Java, that implements the Caesar substitution cipher with k=3. That is, each letter...
    asked 41 minutes ago
  • Design a function named findMax that accepts two integer values as arguments and returns the value...
    asked 47 minutes ago
  • In MIPS, I am trying to create an array of 7 words that can either be...
    asked 48 minutes ago
  • Cash, $2,000 Accounts Receivable, $1,250 Professional Equipment, $10,200 Office Equipment, $5,500 Accounts Payable, $3,500 P. Palmer,...
    asked 49 minutes ago
  • Add two more statements to main() to test inputs 3 and -1. Use print statements similar...
    asked 50 minutes ago
  • C++ program called that reads a string and check if it’s well-formed or not. ex== The...
    asked 1 hour ago
  • 1: Describe five functions of nonverbal communication. (Creating and maintaining relationships, Regulating Interaction, Influencing others, Concealing/deceiving,...
    asked 1 hour ago
  • Trucks that travel on highways have to stop at various locations to be weighed and inspected...
    asked 1 hour ago