- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements