Evaluate an array expression with numbers, + and - in C++


In this problem, we are given an array arr[] consisting of n character values denoting an expression. Our task is to evaluate an array expression with numbers, + and –. 

The expression consists of only, numbers, ‘+’ character and ‘- ’ character.

Let’s take an example to understand the problem,

Input: arr = {“5”, “+”, “2”, “-8”, “+”, “9”,}

Output: 8

Explanation: 

The expression is 5 + 2 - 8 + 9 = 8

Solution Approach:

The solution to the problem is found by performing each operation and then returning the value. Each number needs to be converted to its equivalent integer value.

Program to illustrate the working of our solution,

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;

int solveExp(string arr[], int n) {
   
   if (n == 0)
   return 0;
   int value, result;
   result = stoi(arr[0]);

   for (int i = 2; i < n; i += 2)
   {
      int value = stoi(arr[i]);
      if (arr[i - 1 ] == "+")
         result += value;
      else
         result -= value;
   }
   return result;
}

int main() {
   
   string arr[] = { "5", "-", "3", "+", "8", "-", "1" };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The solution of the equation is "<<solveExp(arr, n);
   return 0;
}

Output −

The solution of the equation is 9

Updated on: 22-Jan-2021

198 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements