Evaluate an array expression with numbers, + and –

15 Jun, 2022
Given an array arr[] of string type which consists of strings “+”, “-” and Numbers. Find the sum of the given array. Examples :  
Input : arr[] = {"3", "+", "4", "-", "7", "+", "13"}
Output : Value = 13
The value of expression 3+4-7+13 is 13.

Input : arr[] = { "2", "+", "1", "-8", "+", "13"}
Output : Value = 8
 
Approach : 1) First of all, initialize the sum i.e, sum = 0. 2) Start traversing the array. 3) As there is string of numbers at every even position of the array, so convert this string into integer and store in a variable value by using stoi function in C++. 4) As there is operator at every odd position, check if the operator is ‘+’ or ‘-‘. If it is ‘+’, then add the value to the sum, else subtract from the sum. 5) Finally, return the sum obtained.Below is the implementation of the above approach : 
C++
Java
Python 3
C#
PHP
Javascript
// C++ program to find sum of given array of// string type in integer form#include <bits/stdc++.h>using namespace std; // Function to find the sum of given arrayint calculateSum(string arr[], int n){      // if string is empty    if (n == 0)       return 0;     string s = arr[0];     // stoi function to convert    // string into integer    int value = stoi(s);    int sum = value;     for (int i = 2; i < n; i = i + 2)    {        s = arr[i];         // stoi function to convert        // string into integer        int value = stoi(s);         // Find operator        char operation = arr[i - 1][0];         // If operator is equal to '+',        // add value in sum variable        // else subtract        if (operation == '+')            sum += value;        else            sum -= value;    }    return sum;} // Driver Functionint main(){    string arr[] = { "3", "+", "4", "-",                     "7", "+", "13" };    int n = sizeof(arr) / sizeof(arr[0]);      cout << calculateSum(arr, n);      return 0;}
// Java program to find sum of given array of// string type in integer formimport java.io.*; class GFG {         // Function to find the sum of given array    public static int calculateSum(String arr[], int n)    {        // if string is empty        if (n == 0)        return 0;        String s = arr[0];                 // parseInt function to convert        // string into integer        int value = Integer.parseInt(s);        int sum = value;             for (int i = 2; i < n; i = i + 2)        {            s = arr[i];                 // parseInt function to convert            // string into integer            value = Integer.parseInt(s);                 // Find operator            char operation = arr[i - 1].charAt(0);                 // If operator is equal to '+',            // add value in sum variable            // else subtract            if (operation == '+')                sum += value;            else                sum -= value;        }        return sum;    }     // Driver code    public static void main (String[] args)    {        String arr[] = { "3", "+", "4", "-",                        "7", "+", "13" };        int n = arr.length;        System.out.println( calculateSum(arr, n));    }} // This code in contributed by Upendra bartwal
# Python3 program to find sum of given# array of string type in integer form # Function to find the sum of given arraydef calculateSum(arr, n):     # if string is empty    if (n == 0):        return 0     s = arr[0]     # stoi function to convert    # string into integer    value = int(s)    sum = value     for i in range(2 , n, 2):             s = arr[i]         # stoi function to convert        # string into integer        value = int(s)         # Find operator        operation = arr[i - 1][0]         # If operator is equal to '+',        # add value in sum variable        # else subtract        if (operation == '+'):            sum += value        else:            sum -= value         return sum # Driver Functionarr = ["3", "+", "4", "-","7", "+", "13"]n = len(arr)print(calculateSum(arr, n)) # This code is contributed by Smitha
// C# program to find sum of given array of// string type in integer formusing System; class GFG {         // Function to find the sum of given array    public static int calculateSum(string []arr,                                          int n)    {                 // if string is empty        if (n == 0)            return 0;        string s = arr[0];                 // parseInt function to convert        // string into integer        int value = int.Parse(s);        int sum = value;             for (int i = 2; i < n; i = i + 2)        {            s = arr[i];                 // parseInt function to convert            // string into integer            value = int.Parse(s);                 // Find operator            char operation = arr[i - 1][0];                 // If operator is equal to '+',            // add value in sum variable            // else subtract            if (operation == '+')                sum += value;            else                sum -= value;        }                 return sum;    }     // Driver code    public static void Main ()    {        string []arr = { "3", "+", "4", "-",                           "7", "+", "13" };        int n = arr.Length;                 Console.Write(calculateSum(arr, n));    }} // This code in contributed by nitin mittal.
<?php// php program to find sum of given// array of string type in integer form // Function to find the// sum of given arrayfunction calculateSum($arr,$n){         // if string is empty    if ($n == 0)    return 0;     $s = $arr[0];     // stoi function to convert    // string into integer    $value = (int)$s;    $sum = $value;    for ($i = 2; $i < $n; $i = $i + 2)    {        $s = $arr[$i];                 // cast to convert        // string into integer        $value = (int)$s;         // Find operator        $operation = $arr[$i - 1];         // If operator is equal to '+',        // add value in sum variable        // else subtract        if ($operation == '+')            $sum += $value;        else if ($operation == '-')            $sum -= $value;    }    return $sum;}     // Driver code    $arr = array("3", "+", "4", "-",                 "7", "+", "13" );    $n = sizeof($arr) / sizeof($arr[0]);    echo calculateSum($arr, $n); // This code is contributed by mits?>
<script>    // Javascript program to find sum of given array of    // string type in integer form            // Function to find the sum of given array    function calculateSum(arr, n)    {                   // if string is empty        if (n == 0)            return 0;        let s = arr[0];                   // parseInt function to convert        // string into integer        let value = parseInt(s);        let sum = value;               for (let i = 2; i < n; i = i + 2)        {            s = arr[i];                   // parseInt function to convert            // string into integer            value = parseInt(s);                   // Find operator            let operation = arr[i - 1][0];                   // If operator is equal to '+',            // add value in sum variable            // else subtract            if (operation == '+')                sum += value;            else                sum -= value;        }                   return sum;    }         let arr = [ "3", "+", "4", "-", "7", "+", "13" ];    let n = arr.length;     document.write(calculateSum(arr, n));         // This code is contributed by vaibhavrabadiya117.</script>
Output :  
13 
Time Complexity: O(n)Auxiliary Space: O(1)
Evaluate an array expression with numbers, + and – | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersEvaluate an array expression with numbers, + and – | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:12•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=oVW1_g7AnIg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
 
Mithun Kumar
nitin mittal
Smitha Dinesh Semwal
vaibhavrabadiya117
geekygirl2001
expression-evaluation
Arrays
Strings
Arrays
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.