Evaluate Mathematical Function from String [closed] - c

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Can you give me some ideas about how can I make a simple mathematical expression parser in C?
User enters a mathematical function in a string and from the string I want to create the function in C.
eg. x + sin(2*x)
-> return x + sin(2x);
Thanks in advance.

You can parse the expression based "Shunting-Yard Algorithm" http://en.wikipedia.org/wiki/Shunting-yard_algorithm. You will need to extend to handle the function calls such as sin, cos etc...

This is not a simple thing to do at all, in face, it's a hard thing. You need a full grammar parser, combined with pre-defined constants/functions (sin, log, pi, etc).
If you have no extensive previous experience with C I would disrecommend doing this, but if you really want to do this look at recursive descent parsing which is arguably the easiest way to do this (without putting a burden on the user, like reverse polish notation).
Last but not least you say you want to create a C function from the user-generated input. This is almost always a wrong thing to do - generating code from user input, instead the easiest approach is pre-processing to create a intermediate representation that can be efficiently executed.

Writing an expression parser and evaluator is one of the usual examples used when discussions parser writing techniques.
For example you could look the documentation for flex/bison or lex/yacc. That will have examples of constructing parsers/expression evaluators.

One way to do it is to use reverse polish notation for the expressions and a stack for the operands.
Some quick pseudo-code:
if element is operand
push in stack
else if element is operation
pop last 2 elements
perform operation
push result in stack
Repeat till end of expression. Final result is the only element in stack.

Related

Converting data to code [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
In C, I'd like to make a macro called TEST() that takes a valid C arithmetic expression and prints and evaluates it. So as an example, if I were to give it TEST(5*2+3) it would print to console 5*2+3 = 13. Unfortunately, I don't know how to convert an expression to a string nor do I know how to take a given string and evaluate it as code. How would I do this?
You can use the stringification operator to turn the argument into a string, then expand into a printf() call that prints the string and the result. My code assumes that the expression is always an int.
#define TEST(EXP) printf("%s = %d\n", #EXP, (EXP))
For the parsing part of your question:
The Shunting-yard algorithm is what you're after.
It is the most common way (that I know of) to convert a mathematical expression represented by a string of characters into a postfixed version(operators come after the operands instead of between), which is much easier to interpret with code.
Good luck!

how can I create a truth table in turbo c [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a project where I will create a truth table, and the user will input propositions and its operator and my program will output the truth values providing with a truth table.
I have following questions:
can I use parsing techniques using turbo c?
how should I parse this expression in turbo c? Ex. (p ^ q) -> r
Once I have the expression parsed, how should I go about generating the truth table? Each section of the expression needs to be divided up into its smallest components and re-built from the left side of the table to the right. How would I evaluate something like that?
Can anyone provide me with tips (or links) concerning the parsing of these arbitrary expressions and eventually evaluating the parsed expression?
Let me try to answer your questions.
Yes. There is no reason why you can't.
You need to write some sort of lexer to turn the expression into tokens. Then you can use the shunting yard algorithm to turn the expression into something you can easily evaluate.
Use the result from (2) and evaluate it in a little stack machine. Set each free variable to all possible combinations to generate a truth table.
Parsing arbitrary languages is not possible in general. A good introduction into compiler construction (which is the subfield you are interested in) is found in the Dragon Book (Compilers: Principles, Techniques, and Tools). It's a large field though, I recommed you to take a compiler construction class.
Also, consider ditching Turbo C for something recent. Turbo C is ancient and full of weird quirks.

Recursive coroutines in C (C99) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
While implementing a communication protocol, we have an encoder that traverses some structs recursively and encodes them into a binary message.
So far so good, but now the buffer has to split out into multiple chunks of fixed size, e.g. the upper size of receiving buffer. Since allocating memory for the full message and cutting it consequently seems to be too wasteful (the size of the message is --in theory-- not bounded), the idea is now to implement a coroutine with means of setjmp/longjmp.
At the moment, I have a prototype with two jump buffers - one buffer for resuming the encode function and the second one for simulating the return behavior of the function to jump back to its caller.
Well, it seems to work, but the code looks like coming straight from hell. Are there any 'conventions' for implementing interruptible recursive functions, maybe a set of macros or something? I would like to use only standardized functions, no inline asm in order to stay portable.
Addition:
The prototype is here: https://github.com/open62541/open62541/compare/master...chunking_longjmp
The 'usage' is shown inside of the unit-test.
Currently, coroutine behavior is implemented for a non-recursive function Array_encodeBinary. However, the 'coroutine' behavior should be extended to the general recursive UA_encodeBinary function located here: https://github.com/open62541/open62541/blob/master/src/ua_types_encoding_binary.c#L1029
As pointed out by Olaf the easiest way would be to use an iterative algorithm. However, if for some reason this is difficult, you can always simulate the recursive algorithm with a stack container and a while loop. This at least makes the function easier to interrupt. Pretty good article of how to implement this can be found here. The article is written for c++, but it should not be difficult to convert it to c.

C Program Function [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I don't want an answer in the form of code, but I do need to know how to start working on this problem. I have just begun learning C language and during the learning process, I am stuck with this confusing question. The question is as follows:
Write a function to compute the distance between two points and use it to develop another function that will compute the area of the triangle whose vertices are *A(x1,y1), B(x2,y2), and C(x3,y3).* Use these functions to develop a function which returns the value 1 if the point (x,y) lines inside the triangle ABC, otherwise returns a value 0.
Please suggest me the appropriate coding for this problem in C language and kindly include comments for better understanding.
I know both the formulas by the way.
Approach this problem, like all other coding problems, in increments. Your problem statement states pretty much what you need to do:
first, write a routine to compute the distance between two points. You need to find the formula to do this. Probably easiest to use double variables, be sure to read about how to specify the format statement for printf so that it can print double variables.
next, find the formula to use in order to compute the area of a triangle.
the last step is the hardest, and you will need to use everything you learned in steps one and two. Again, dig out your calculus or algebra book and see how this is done and then write code to do the same thing. It is interesting to see how a math description gets translated to computer code, they are not the same thing and unless you write a lot comments in your code it will be difficult to see how they do the same function.
good luck.
PS. when defining a function that returns a double variable, code:
double distance_calc(double x1, double x2, double y1, double y2)
{
double computed_value;
// do the formula and compute: computed_value = etc.
return computed_value;
}
Hope this helps.

How does one obfuscate code in C? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I want to obfuscate code just for fun. I'm looking at code from the international obfuscated c contest: http://www.ioccc.org/ And I seriously just have no idea how to even start reverse engineering some of this code to make anything of sense.
What are some common obfuscation techniques and how do you make sense of obfuscated code?
There is a lot of different techniques to obfuscate code, here is a small, very incomplete list:
Identifier mangling. Either you will find people using names like a, b, c exclusively, or you find identifiers that have absolutely nothing to do with the actual purpose of the variable/function. Deobfuscation would be to assign sensible names.
Heavy use of the conditional evaluation operator ? :, replacing all occurences of if() else. In most cases that's a lot harder to read, deobfuscation would reinsert if().
Heavy use of the comma operator instead of ;. In combination with 2. and 4., this basically allows the entire program to be one single statement in main().
Recursive calls of main(). You can fold any function into main by having an argument that main can use to decide what to do. Combine this with replacing loops by recursion, and you end up with the entire program being the main function.
You can go the exact opposite direction to 3. and 4., and hack everything into pieces by creating an insane amount of functions that all do virtually nothing.
You can obfuscate the storage of an array by storing the values on the stack. Should you need to walk the data twice, there's always the fork() call handy to make a convenient copy of your stack.
As I said, this is a very incomplete list, but generally, obfuscation is usually the heavy, systematic abuse of any valid programming technique. If the IOCCC were allowing C++ entries, I would bet on a lot of template code entering, making heavy use of throwing exceptions as an if replacement, hiding structure behind polymorphism, etc.

Resources