Normally, you have to define the priority of each operation and process each of them one by one.
First your expression is: '`[ 5,-1, 6,-4,20,-2, 4]`'
Do all '/' first: '`[ 5,-1, 6,-4, 5,-1, 0]`' <- 20/ 4 = 5+0
Then, do all '*': '`[ 5,-1,30,-1, 0,-1, 0]`' <- 6* 5 = 30+0
Then, do all '-': '`[ 5,-1,30,-1, 0,-1, 0]`' <- Nothing
Then, do all '+' (sum positive): '`[35,-1, 0,-1, 0,-1, 0]`' <- 5+30+0+0 = 35 + 0 + 0
ADDED: Here is the C code.
void ShowArray(int pX[], int pLength) {
int i;
for(i = 0; i < pLength; i++)
printf("%3d ", pX[i]);
printf("\n");
}
void ShiftArray(int pX[], int pIndex, int pSkip, int pLength) {
int i;
for(i = pIndex; i < (pLength - pSkip); i++)
pX[i] = pX[i + pSkip];
for(i = (pLength - pSkip); i < pLength; i++)
pX[i] = 0;
}
int main(void) {
const int OPERCOUNT = 4;
const int PLUS = -1; // -1 Do last
const int SUBT = -2;
const int MULT = -3;
const int DIV = -4; // -4 Do first
int X[] = {5, PLUS, 6, MULT, 20, DIV, 4};
int XCount = 7;
ShowArray(X, XCount);
int i;
for(i = OPERCOUNT; --i >= 0; ) {
int OPER = -(i + 1);
int j = 0;
for(j = 0; j < XCount; j++) {
int x = X[j];
if (x == OPER) {
if (x == PLUS) X[j - 1] = X[j - 1] + X[j + 1];
else if (x == SUBT) X[j - 1] = X[j - 1] - X[j + 1];
else if (x == MULT) X[j - 1] = X[j - 1] * X[j + 1];
else if (x == DIV ) X[j - 1] = X[j - 1] / X[j + 1];
ShiftArray(X, j, 2, XCount);
}
}
ShowArray(X, XCount);
}
int Sum = 0;
int j;
for(j = 0; j < XCount; j++) {
int x = X[j];
if (x > 0) Sum += x;
}
printf("Result: %d\n", Sum);
}
And here is the result:
5 -1 6 -3 20 -4 4
5 -1 6 -3 5 0 0
5 -1 30 0 0 0 0
5 -1 30 0 0 0 0
35 0 0 0 0 0 0
Result: 35
This should works.
Enjoy coding.