# Thread: arithmetic calculation

1. ## arithmetic calculation

Hi there..

Could somebody explain to me how to use gets instead of scanf?? And also...how do u use the function atoi? I know you need it to convert strings to integer but there's no specific example in the book.

Well my problem actually concerns arithmetic calculation. (+,- ,*,/) I need to ask the user for input and then show them the result. eg.

input : 12 +3 /5
result : 1

I'm not asking anybody for code, just some ideas on how to go about it.

I had a basic idea about it but it doesnt seem to work. I think you're suppose to store the input into an array, and run through each element of the array, correct?

So, ok I declare something like

char str [10];
/* I probably have declare other stuffs as well*/

printf("Enter input"); /* user inputs a string, the somehow i
need to convert it to integers?*/
gets()/* is this how you use gets??*/

/* do the math here */

printf("Result : %d");

I'm sorry if this looks silly but I hope somebody is willing to help. Thanx..

2. >>>Could somebody explain to me how to use gets instead of scanf??
NO! Definately not. Don't use gets(), it's bad

You need fgets() to get a string from the user.
Code:
```#include <stdio.h>
#include <stdlib.h>

int main(void)
{
char buf[BUFSIZ];

printf("Enter number: ");

if (fgets(buf, sizeof buf, stdin) != NULL)
{
printf ("\nYou entered %d\n", atoi(buf));
}
return 0;
}```
This example assumes that the user enterd a valid number, if not, it'll be turned into 0. You may want to validate the data manually first.

Hope this helps.

3. ## Re: arithmetic calculation

Originally posted by wombat
Well my problem actually concerns arithmetic calculation. (+,- ,*,/) I need to ask the user for input and then show them the result. eg.

input : 12 +3 /5
result : 1

I'm not asking anybody for code, just some ideas on how to go about it.

I had a basic idea about it but it doesnt seem to work. I think you're suppose to store the input into an array, and run through each element of the array, correct?
Mathematical expression parsing is a bit more complex than storing the bits in an array and going through them.

First of all, analysis of expressions is much easier if the expressions are presented to the analyser program in something called Reverse Polish Notation (RPN). This is where the operands preceed the operator. For example in standard infix notation, you might write 2 + 5, this would be 2 5 + in RPN. One good thing about this system is that it forms a parentheses-free system. It is also well suited to computer manipulation because its format suits itself to use with a stack (first-in, last-out) data structure.

Let's consider the infix expression, (3 + 5) * (9 - 7). To evaluate this, we would apply the rules of precedence, i.e. parentheses, exponentiation, multiplication and division etc. We would thus be able to evaluate this expression to 16. Let's consider how we actually do that in our mind.

First we get the number 3 and then get the number 5. We add them together and store the result (8). We then get the number 9 and the number 7, storing the result of their subtraction (2). Finally, we multiply them together to get the final result of 16. We have really just converted this expression to RPN form in our head in order to process it. The RPN form is 3 5 + 9 7 - *. This form, reading from left to right is much more descriptive of the logical steps taken to process the statement, first add 3 and 5 (3 5 +), then subtract 7 from 9 (9 7 -), and then multiply those two results together (*). You can see that RPN form reads in the logical order of evaluation, and there is therefore no need for parentheses.

This logical order leads to two very simple rules for evaluating an RPN statement:

1. The next symbol encountered must be loaded on to the stack if it is an operand (e.g. a number or variable).

2. If the next symbol encountered is an operator (e.g. '+', '-' etc.), then carry out the required operation on the top two items of the stack. The result of this operation must then be left on the top of the stack.

I wish that RPN notation was used instead of infix notation as it's so much more logical, but that's just me trying to change the world again .

This is all very good, but I expect you will want your users to input an infix expression, so you need to know how to convert from an infix expression to RPN. This is actually not too hard either. You can use a binary tree data structure.

I don't have time currently to go through the process of infix -> RPN conversion, but I'm sure a Google search would yield helpful results.

I hope I've given you a starter...

Good Luck,

4. Here is a free parser I often use. It only works with integers though.
Code:
```int	op_plus(int a,int b)
{
return (a+b);
}

int	op_moins(int a,int b)
{
return (a-b);
}

int	op_div(int a,int b)
{
return (a/b);
}

int	op_mul(int a,int b)
{
return (a*b);
}

int	op_mod(int a,int b)
{
return (a%b);
}

struct s_op
{
char c;
int  p;
int  (*f)();
} ;

typedef	struct s_op	t_op;

t_op	op [] =
{
{'+',1,op_plus},
{'-',1,op_moins},
{'/',2,op_div},
{'*',2,op_mul},
{'%',2,op_mod},
{0,0,0}
};

int	find_last_op(char *str,int p)
{
int	pos;
int	i;
int	ret;
int	par;

ret = -2;
par = 0;
pos = strlen(str)-1;
while (pos>=0)
{
if (str[pos] == ')')
par ++;
if (str[pos] == '(')
par --;
i = 0;
while (!par && op[i].c)
{
if (op[i].c==str[pos])
{
ret = -1;
if (op[i].p==p)
return (pos);
}
i ++;
}
pos --;
}
return (ret);
}

int	is_nb(char *str)
{
if (*str=='(')
{
str[strlen(str)-1] = 0;
return (eval_expr_sub(str+1,0));
}
return (atoi(str));
}

int	eval_expr_sub(char *str,int p)
{
int	pos;
char	save;
int	nb2;

if ((pos = find_last_op(str,p))==-1)
return (eval_expr_sub(str,p+1));
if (pos==-2)
return (is_nb(str));
nb2 = eval_expr_sub(str+pos+1,p+1);
save = str[pos];
str[pos] = 0;
pos = 0;
while (op[pos].c)
{
if (save==op[pos].c)
return (op[pos].f(eval_expr_sub(str,p),nb2));
pos ++;
}
printf("PB !!!\n");
return (0);
}

int	Evaluate(char *str)
{
return (eval_expr_sub(str, 0));
}```
Just pass the function Evaulate a string with the expression to parse. It will return a int which is the final value.

Hope this helps.

- Sean

Popular pages Recent additions