# Thread: processing of user inputted mathematical expression

1. ## processing of user inputted mathematical expression

A. I am trying to develop a curve plotter which takes in user inputted equations[ eg y=t*t + cos(4*t) , x = 2*sin t ]

Then a loop is used

for(t=0; t<=10; t+=.1)
{
y = t*t + cos(4*t) ;
x = 2*sin t;
putpixel(fun1(x), fun2(y), WHITE); // fun1 and fun2 return appropriate pixel number
}

How can the user input the equations when the program runs?

2. Try getting all the input with fgets() and then start converting.

3. ## I don't know about ' converting' the string obtained after fgets()

Referring to the reply by respected Mr. Vber,

I do not understand what is meant by " converting" the string obtained by fgets().

As it is clear from the code, I need to have the equations in the form of C code and then use them inside the loop.
I need to do this without having to compile the code again
after modifying the source file.

for(t=0; t<=10; t+=.1)
{
y = t*t + cos(4*t) ; // user inputted equations
x = 2*sin t;
putpixel(fun1(x), fun2(y), WHITE); // fun1 and fun2 return appropriate pixel number
}

I am using Borland C compiler on a DOS platform.

4. >I do not understand what is meant by " converting" the string obtained by fgets().
C cannot evaluate expressions in string format, you have to manually break the string into tokens, identify them, and evaluate them. Here is a simple way to evaluate simple expressions. More complete solutions have already been given before, try searching the C and C++ boards.
Code:
#include <stdio.h>

static int eval ( int l, char op, int r )
{
int ret = 0;

switch ( op ) {
case '+': ret = l + r; break;
case '-': ret = l + r; break;
case '*': ret = l + r; break;
case '/': if ( r != 0 ) ret = l + r; break;
}

return ret;
}

int main ( void )
{
char s[] = "1 + 1";
int lhs, rhs;
char op;

if ( sscanf ( s, "%d %c %d", &lhs, &op, &rhs ) == 3 )
printf ( "%s == %d\n", s, eval ( lhs, op, rhs ) );

return 0;
}
-Prelude

5. We can use tree structure to obtain solution of any expression.

Just scanning input expression one character at a time and inserting into proper place in the tree.

Then evaluating the expression by parsing through it.

There are lots of tutorials on doing this.