Need help with an assignment

Write a c++ program to solve the following expression,
[ 2a - 4b +3ab -5a +2b ] .

I have not idea where to begin. If anyone could give me some suggestions as to how I could tackle this program, it would be greatly appreciated.
Well, I don't know either. I don't see anything to solve there, so perhaps the problem statement should define what it means by "solve". Normally one "solves" an equation by finding the values or range of values for its variables that make the equation true, but that's not an equation, so that can't be it.
Last edited on
I think what my professor means by solve is to simplify the expression, but I don't know a route to feed this into variables. I was thinking of pairing each variable and its coefficients into data structures, but how get a structure to pull from the string "2a - 4b + 3ab - 5a + 2b?" I feel like this is a more advanced option than what my professor is expecting.
Last edited on

Post the exact text of the assignment, then we can all be on the same page :+)
professor means by solve is to simplify the expression

Then he probably means to add/subtract like terms.

If it's only addition and subtraction then it's relatively easy.

Step 1: Split string into substrings.
Better to use stringstreams. I donno if people ever use strtok() in C++, it's a C function.

Step 2: Parse the substrings.
Iterate over the substrings like so:
--> If value isn't a +/- then append it to an array "Variables"
--> If value is +/- then ditch it and set a bool variable to true.
--> When the bool variable is true, the next to be appended gets a - (unary minus)
Then set back the bool to false after appending.

You will now have an array of terms.

Step 3: Iterate over the array finding like terms.
Little more complex.
--> You've got to find the variable of each term and keep it in memory (an array)
That means you will have to ignore the (-) and the numbers, you can store them too if you want.
--> For every new variable you find, you will compare it with every element of the array.
If you find a like element then you will add the constant parts of the two terms and pop the successive terms.

Once you're done with one iteration, your equation is simplified.

Step 4: Obtain a string for the simplified equation
Simply append all values to a string. If you want you can make it so that when there's a negative value, you first append a '-' followed by a space and then the absolute value.

Exception handling is up to you.
Registered users can post here. Sign in or register to post.