- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- C++ Program to Evaluate an Expression using Stacks
- Program to evaluate ternary expression in C++
- Program to build and evaluate an expression tree using Python
- Evaluate Postfix Expression
- Evaluate a boolean expression represented as string in C++
- Why does the JavaScript void statement evaluate an expression?
- C Program to Minimum and Maximum prime numbers in an array
- Evaluate the lowest cost contraction order for an einsum expression in Python
- Find All Numbers Disappeared in an Array in C++
- Maximum consecutive numbers present in an array in C++
- C++ code to decrease even numbers in an array
- Split an array of numbers and push positive numbers to JavaScript array and negative numbers to another?
- Looping numbers with object values and push output to an array - JavaScript?
- Difference between numbers and string numbers present in an array in JavaScript
- C program to find the second largest and smallest numbers in an array

Advertisements