# Thread: Having some problem with my simple calculator

1. ## Having some problem with my simple calculator

I am just a newbie in programming.

Code
__________________________________________________

#include <stdio.h>

char result(char);

void main()
{

char opr, a = 'Y';
float num[100], ans, total=0;

do{

int counter=0;

do{

scanf("%f", &num[counter]);

if(counter>0)
{

if (opr == '+')
ans += num[counter];

if(opr == '-')
ans -= num[counter];

if (opr == '*')
ans *= num[counter];

if (opr == '/')
ans /= num[counter];

}

else
{
ans = num[counter];
}

total=ans;

opr=getchar();
opr=getchar();

if (opr == '=')
printf("Total is %.2f", total);

counter++;

}while (opr != '=');

}while (result(a) == 'Y');
}

char result (char x)
{

printf("\nDo you wish to continue?\n(Y/N)\n");

}

_________________________________________________

How do I compare the operators inserted by the user. We know that the * operator comes before + or - operator. For example,

1+2*3=7

but my simple calculator only performs

1+2*3=9

how do I code it in a way that it follows the rules of operators precedence.

(*This is an assignment)

2. void main()

This is wrong. Don't use 'void main'. Use 'int main' and return a value at the end of the main function.

printf("\nDo you wish to continue?\n(Y/N)\n");

Why are you scanning two values into the same variable here?

how do I code it in a way that it follows the rules of operators precedence.

Loop through the array of input tokens. Search for whatever has the highest precidence. When you find it, apply the values to the items on each side. For example:

num[0] = 5
num[1] = +
num[2] = 3
num[3] = *
num[4] = 6

loop through, find the *, then multiply the item before it to the item beyond it. Then squish the array by removing the stuff you've already covered.

num[0] = 5
num[1] = +
num[2] = 18
num[3] = empty
num[4] = empty

Quzah.

3. we just did a calculator contest. there's some source code in the general board.

4. I know a lot of teachers will teach the use of
void main( ) and never introduce the students
to int main( void ). What a shame. I think they
believe it's for simplicity, but it's plain wrong.
Go with...
Code:
```int main( void )
//code here
return 0;```
-fox