Answer to Question #241387 in C for Pranav

Question #241387
C language. Write a program that will accept a basic arithmetic problem from the user and solve each portion using various processes before returning the value to the parent process. Don't worry about the order of operations, for example:

Enter problem:

30 - 2 * 2 / 8 - 3

PID 20421 calculated 30-2 as 28

PID 20422 calculated 28*2 as 56

PID 20423 calculated 56/8 as 7

PID 20424calculated 7-3 as 4

Final result: 4

(program: only integers, no calculation greater than 255, use WEXITSTATUS(value) on exit for value)

Then implement another program with same math process with each calculation as a different single thread.
1
Expert's answer
2021-09-23T17:45:39-0400
#include <iostream>
#include <bits/stdc++.h>
using namespace std;


int pred(char op){
	if(op == '+'||op == '-')
	return 1;
	if(op == '*'||op == '/')
	return 2;
	return 0;
}


int perform_opr(int a, int b, char op){
	switch(op){
		case '+': return a + b;
		case '-': return a - b;
		case '*': return a * b;
		case '/': return a / b;
	}
}


int evaluate(string t){
	int i;
	stack <int> vals;
	stack <char> ops;
	
	for(i = 0; i < t.length(); i++){
		if(t[i] == ' ')
			continue;
		else if(t[i] == '('){
			ops.push(t[i]);
		}
		else if(isdigit(t[i])){
			int val = 0;
			while(i < t.length() &&
						isdigit(t[i]))
			{
				val = (val*10) + (t[i]-'0');
				i++;
			}
			
			vals.push(val);
			i--;
		}
		else if(t[i] == ')')
		{
			while(!ops.empty() && ops.top() != '(')
			{
				int v2 = vals.top();
				vals.pop();
				
				int v1 = vals.top();
				vals.pop();
				
				char op = ops.top();
				ops.pop();
				
				vals.push(perform_opr(v1, v2, op));
			}
			
			if(!ops.empty())
			ops.pop();
		}
		
		else
		{
			while(!ops.empty() && pred(ops.top())
								>= pred(t[i])){
				int v2 = vals.top();
				vals.pop();
				
				int v1 = vals.top();
				vals.pop();
				
				char op = ops.top();
				ops.pop();
				
				vals.push(perform_opr(v1, v2, op));
			}
			ops.push(t[i]);
		}
	}
	
	while(!ops.empty()){
		int v2 = vals.top();
		vals.pop();
				
		int v1 = vals.top();
		vals.pop();
				
		char op = ops.top();
		ops.pop();
				
		vals.push(perform_opr(v1, v2, op));
	}
	
	return vals.top();
}


int main() {
	cout << evaluate("30 - 2 * 2 / 8 - 3") << "\n";
	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS