Instantiating a variable in a mathematical expression - c++

I am trying to code a C++ app that will be able to calculate a mathematical expression. Doing so I must convert a infix expression into a postfix expression and then calculate the value.
Before I can start with the conversion of the infix expression into a postfix expression and to calculate it I must first instantiate the x and y by giving it values. My question is this. How can I search for x and y in the 'expr' string in the instantiateVariable function and assign the values to it (as it is done in the main.cpp) when its found?
I'm quite sure one can use a for loop but how should I be doing it? Any help will be appreciated.
main.cpp
int main()
{
Expression expr("x + y + sqrt 25 - 3");
expr.instantiateVariable('x',5);//Set x = 5
expr.instantiateVariable('y',3);//Set y = 3
/*
The output of the following statement should be:
Answer: 10
*/
cout<<"Answer: "<<expr.evaluate()<<endl;
}
and in my header folder I have the following:
Expression.h
class Expression
{
public:
Expression(string expr);
~Expression();
void instantiateVariable(char name, int value);
int evaluate();
};

I would go for a naive Shunthing-yard. The principle is easy:
Reach each operand and put them on a queue
Every time you encounter an operator put it on a stack
If the operator on top of the stack has a higher precedence pop it and add it to the queue (it needs to be calculated first)
Continue until the end of the expression and then pop everything to the queue
supporting parenthesis is also easy with this method.
Some parsing is obviously required (a tokenization to be precise) but this is going to be pretty straightforward.

Related

How does recursion work when there are two recursive calls in a same statement?

I have recently taken up studying algorithms and data structures.I came across fibonacci problem and its solution using recursion. But thats the thing. I understand how recursive calls work when there is only one(like in factorial of a number).The function calls keep on stacking up until they hit the base case and then they start unraveling by one to the desired answer.
But What I dont get is how does recursion work when there are two recursive calls in an expression like f(n)+f(n/2). I mean which call is resolved first and when does the second call gets resolved. Also how is the sum calculated if this expression is assigned to a statement?
I wrote a small code to decipher this myself.
#include <iostream>
#include <string>
int main()
{
int recursionTest(int n, char c);
int x;
std::cin>>x;
std::cout<<"Ans:"<<recursionTest(x,'c');
}
int recursionTest(int n,char c)
{
int result=0;
if(n==0)
return 1;
std::cout<<n<<":"<<c<<std::endl;
result=recursionTest(n/2,'L')+recursionTest(n/3,'R');////I cant figure
out the flow of
control here!!!
return result;
}
And I got the following output.
24
24:c
12:L
6:L
3:L
1:L
1:R
2:R
1:L
4:R
2:L
1:L
1:R
8:R
4:L
2:L
1:L
1:R
2:R
1:L
Ans:20
SO I get it ,its a tree structure. But I still dont know how we are getting 20 as answer(input=24). How is the sum expression working and what is it summing,how can I look at the tree structure and generate the same out put?
There is no defined order to how the two subexpressions of the + operator are evaluated. The compiler can emit code to evaluate either one first and the other one second. It can even interleave some computations of one side with computations of the other. For example, it could calculate n/3, then n/2, then the right function call, and finally the left function call.
The flow control is just like for a single case of recursion followed by another single case. So, your line:
result=recursionTest(n/2,'L')+recursionTest(n/3,'R');
is effectively the same as:
int left = recursionTest(n/2,'L');
int right = recursionTest(n/3,'R');
result = left + right;
except for the implication in my version that the left function call is guaranteed to be evaluated before the right function call.
Here operator precedence will play the role
f(n) + f(n/2);
In the above code snippet f(n) will get called first and then f(n/2). basically arithmetic operators compile from left to right.
If you want to debug the code use printf statements inside function f(int) by printing n value . By this you can get the hang of the code

Error when passing negative integer to a function in OCaml

If I define a function in OCaml, for example let f x = x + 1;; and then I try to call it passing a negative number
f -1;; it gives to me the following error
Error: This expression has type int -> int
but an expression was expected of type int
Why this error occurs?
Basically, it comes from the precedence of the parser. The compiler believes that f -1 means you want to subtract f by 1. It has been complained about for ages now.
Typing in f (-1) or f ~-1 will solve your problem (the later using the "explicitly unary minus").
UPDATE:
As stated in the OCaml manual:
Unary negation. You can also write - e instead of ~- e.
Basically, - can be used both as a binary operator 4 - 1 and a unary operator -1. But, as in your case, there can be confusion: f - 1 is "f minus one" and not "f applied to minus one". So the ~- operator was added to have a non-confusing unary minus as well.
Note that the spaces are not significant here, and that won't change because a lot of already existing code may contain operations without space.

What is "from ?: first" In TextMate Source Code regexp.cc [duplicate]

I was writing a console application that would try to "guess" a number by trial and error, it worked fine and all but it left me wondering about a certain part that I wrote absentmindedly,
The code is:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x,i,a,cc;
for(;;){
scanf("%d",&x);
a=50;
i=100/a;
for(cc=0;;cc++)
{
if(x<a)
{
printf("%d was too big\n",a);
a=a-((100/(i<<=1))?:1);
}
else if (x>a)
{
printf("%d was too small\n",a);
a=a+((100/(i<<=1))?:1);
}
else
{
printf("%d was the right number\n-----------------%d---------------------\n",a,cc);
break;
}
}
}
return 0;
}
More specifically the part that confused me is
a=a+((100/(i<<=1))?:1);
//Code, code
a=a-((100/(i<<=1))?:1);
I used ((100/(i<<=1))?:1) to make sure that if 100/(i<<=1) returned 0 (or false) the whole expression would evaluate to 1 ((100/(i<<=1))?:***1***), and I left the part of the conditional that would work if it was true empty ((100/(i<<=1))? _this space_ :1), it seems to work correctly but is there any risk in leaving that part of the conditional empty?
This is a GNU C extension (see ?: wikipedia entry), so for portability you should explicitly state the second operand.
In the 'true' case, it is returning the result of the conditional.
The following statements are almost equivalent:
a = x ?: y;
a = x ? x : y;
The only difference is in the first statement, x is always evaluated once, whereas in the second, x will be evaluated twice if it is true. So the only difference is when evaluating x has side effects.
Either way, I'd consider this a subtle use of the syntax... and if you have any empathy for those maintaining your code, you should explicitly state the operand. :)
On the other hand, it's a nice little trick for a common use case.
This is a GCC extension to the C language. When nothing appears between ?:, then the value of the comparison is used in the true case.
The middle operand in a conditional expression may be omitted. Then if the first operand is nonzero, its value is the value of the conditional expression.
Therefore, the expression
    x ? : y
has the value of x if that is nonzero; otherwise, the value of y.
This example is perfectly equivalent to
    x ? x : y
In this simple case, the ability to omit the middle operand is not especially useful. When it becomes useful is when the first operand does, or may (if it is a macro argument), contain a side effect. Then repeating the operand in the middle would perform the side effect twice. Omitting the middle operand uses the value already computed without the undesirable effects of recomputing it.

C/C++: Passing a string read to a loop inside a program in C

I am working in a program that should read an user inputted string and use that string inside a loop for basic calculation.
My general problem is the use of the string inside a loop and, despite the fact that later it will have to do more, from now I only need to test Bolzano's Theorem (in particular to find possible intervals for roots) for the inputted expression.
I already started working into a function that reads the input char by char and with switch controls calculate the infix expression.
However, what I would like to know is if there is a way to do something like that:
{
/*Already stored the doubles: a, b, precision.*/
printf("Enter the expression you want to calculate");
scanf("%s", expression);
/*User input: (3*i)+(i*i)-3*/
while( i <= b ){
fa = (3*i)+(i*i)-3; /*How to insert the string here*/
fb = (3*(i+precision))+((i+precision)*(i+precision))-3;
if( fa*fb < 0 )
printf("There is at least one root in the interval: [ %g, %g ].", a, a+precision);
/*And goes on...*/
}
Supposing that the user does not input an invalid expression for the use in the loop (such as i^7) or that I already implemented controls to convert those expressions (something like read a string and change it to a postfix or prefix notation doing the necessary conversion), is there a way to use a stored string in a assignment into a loop?
I think what you're asking is: given a string with some mathematical expression, how do I evaluate that expression?
I don't know if you can make certain assumptions about the syntax of the expression; if so that would help you simplify your code. If not, you basically would have to "tokenize" your string first, for above string that would be a sequence of tokens like this:
LBRACKET, NUM, BINOP, VAR, RBRACKET, BINOP, LBRACKET, VAR, BINOP, VAR, RBRACKET, BINOP, NUM
You'd also have to build yourself a little parser that makes sure your expression is formed based on certain syntactic rules; the parser would consume that sequence of tokens. The output of the parser is then a data structure (usually a tree) that represents that expression. Given that tree, you can evaluate the expression by computing sub-expressions bottom up.
fa = -
/ \
+ 3
/ \
* *
/ \ / \
3 i i i
It would be just a matter of adding new nodes into that tree to add your precision operands.
There's some stuff online on how to do this. Just search for "how to build an expression evaluator" and for example this page comes up with some more details.

what's an expression and expression statement in c++?

I've read that usually statements in c++ end with a semi-colon; so that might help explain what an expression statement would be. But then what would you call an expression by giving an example?
In this case, are both just statements or expression statements or expressions?
int x;
x = 0;
An expression is "a sequence of operators and operands that specifies a computation" (that's the definition given in the C++ standard). Examples are 42, 2 + 2, "hello, world", and func("argument"). Assignments are expressions in C++; so are function calls.
I don't see a definition for the term "statement", but basically it's a chunk of code that performs some action. Examples are compound statements (consisting of zero or more other statements included in { ... }), if statements, goto statements, return statements, and expression statements. (In C++, but not in C, declarations are classified as statements.)
The terms statement and expression are defined very precisely by the language grammar.
An expression statement is a particular kind of statement. It consists of an optional expression followed by a semicolon. The expression is evaluated and any result is discarded. Usually this is used when the statement has side effects (otherwise there's not much point), but you can have a expression statement where the expression has no side effects. Examples are:
x = 42; // the expression happens to be an assignment
func("argument");
42; // no side effects, allowed but not useful
; // a null statement
The null statement is a special case. (I'm not sure why it's treated that way; in my opinion it would make more sense for it to be a disinct kind of statement. But that's the way the standard defines it.)
Note that
return 42;
is a statement, but it's not an expression statement. It contains an expression, but the expression (plus the ;) doesn't make up the entire statement.
These are expressions (remember math?):
1
6 * 7
a + b * 3
sin(3) + 7
a > b
a ? 1 : 0
func()
mystring + gimmeAString() + std::string("\n")
The following are all statements:
int x; // Also a declaration.
x = 0; // Also an assignment.
if(expr) { /*...*/ } // This is why it's called an "if-statement".
for(expr; expr; expr) { /*...*/ } // For-loop.
A statement is usually made up of an expression:
if(a > b) // a > b is an expr.
while(true) // true is an expr.
func(); // func() is an expr.
To understand what is an expression statement, you should first know what is an expression and what is an statement.
An expression in a programming language is a combination of one or more explicit values, constants, variables, operators, and functions that the programming language interprets (according to its particular rules of precedence and of association) and computes to produce ("to return", in a stateful environment) another value. This process, as for mathematical expressions, is called evaluation.
Source: https://en.wikipedia.org/wiki/Expression_(computer_science)
In other words expressions are a sort of data items. They can have single or multiple entities like constants and variables. These entities may be related or connected to each other by operators. Expressions may or may not have side effects, in that they evaluate to something by means of computation which changes a state. For instance numbers, things that look like mathematical formulas and calculations, assignments, function calls, logical evaluations, strings and string operations are all considered expressions.
function calls: According to MSDN, function calls are considered expressions. A function call is an expression that passes control and arguments (if any) to a function and has the form:
expression (expression-list opt) which is invoked by the ( ) function operator.
source: https://msdn.microsoft.com/en-us/library/be6ftfba.aspx
Some examples of expressions are:
46
18 * 3 + 22 / 2
a = 4
b = a + 3
c = b * -2
abs(c)
b >= c
c
"a string"
str = "some string"
strcat(str, " some thing else")
str2 = "some string" + " some other string" // in C++11 using string library
Statements are fragments of a program that execute in sequence and cause the computer to carry out some definite action. Some C++ statement types are:
expression statements;
compound statements;
selection statements;
iteration statements;
jump statements;
declaration statements;
try blocks;
atomic and synchronized blocks (TM TS).
Source: http://en.cppreference.com/w/cpp/language/statements
I've read usually statements in c++ ends with a semicon;
Yes usually! But not always. Consider the following piece of code which is a compound statement but does not end with a semicolon, rather it is enclosed between two curly braces:
{ // begining of a compound statement
int x; // A declaration statement
int y;
int z;
x = 2; // x = 2 is an expression, thus x = 2; with the trailing semicolon is an expression statement
y = 2 * x + 5;
if(y == 9) { // A control statement
z = 52;
} else { // A branching statement of a control statement
z = 0;
}
} // end of a compound statement
By now, as you might be guessing, an expression statement is any statement that has an expression followed by a semicolon. According to MSDN an expression statement is a statement that causes the expressions to be evaluated. No transfer of control or iteration takes place as a result of an expression statement.
Source: https://msdn.microsoft.com/en-us/library/s7ytfs2k.aspx
Some Examples of expression statements:
x = 4;
y = x * x + 10;
radius = 5;
pi = 3.141593;
circumference = 2. * pi * radius;
area = pi * radius * radius;
Therefore the following can not be considered expression statements since they transfer the control flow to another part of a program by calling a function:
printf("The control is passed to the printf function");
y = pow(x, 2);
side effects: A side effect refers to the modification of a state. Such as changing the value of a variable, writing some data on a disk showing a menu in the User Interface, etc.
Source: https://en.wikipedia.org/wiki/Side_effect_(computer_science)
Note that expression statements don't need to have side effects. That is they don't have to change or modify any state. For example if we consider a program's control flow as a state which could be modified, then the following expression statements
won't have any side effects over the program's control flow:
a = 8;
b = 10 + a;
k++;
Wheres the following expression statement would have a side effect, since it would pass the control flow to sqrt() function, thus changing a state:
d = sqrt(a); // The control flow is passed to sqrt() function
If we consider the value of a variable as a state as well, modifying it would be a side effect thus all of expression statements above have side effects, because they all modify a state. An expression statement that does not have any side effect is not very useful. Consider the following expression statements:
x = 7; // This expression statement sets the value of x to 7
x; // This expression statement is evaluated to 7 and does nothing useful
In the above example x = 7; is a useful expression statement for us. It sets the value of x to 7 by = the assignment operator. But x; evaluates to 7 and it doesn't do anything useful.
According to The C++ Programming Language by Bjarne Stroustrup Special(3rd) Edition, a statement is basically any declaration, function call, assignment, or conditional. Though, if you look at the grammar, it is much more complicated than that. An expression, in simple terms, is any math or logical operation(s).
The wikipedia links that ok posted in his answer can be of help too.
In my opinion,
a statement *states* the purpose of a code block. i.e. we say this block of code if(){} is an if-statement, or this x=42; is an expression statement. So code such as 42; serves no purporse, therefore, this is *not* a statement.
and,
an expression is any legal combination of symbols that represents a value (Credit to Webopedia); it combines variables and constants to produce new values(Quoted from Chapter 2 in The C Programming Language). Therefore, it also has a mathematical connotation. For instance, number 42 in x=42; is an expression (x=42; is not an expression but rather an expression statement), or func(x) is an expression because it will evaluate to something. On the contrary, int x; is not an expression because it is not representing any value.
I think this excerpt from a technical book is most useful and clear.
Read the paragraphs till the start of 1.4.2 statements would be useful enough.
An expression is "a sequence of operators and operands that specifies a computation"
These are expressions:
1
2 + 2
"hi"
cout << "Hello, World!"
The last one is indeed an expression; << is the output operator, cout (of type ostream) and "Hello, World!" (string literals) are the operands. The operator returns the left-hand operand, so (cout << "Hello, ") << "World!" is also a valid expression but also not a statement.
An expression becomes an expression statement when it is followed by a semicolon:
1;
2 + 2;
"hi";
cout << "Hello, World!";
An expression is part of a statement, OR a statement itself.
int x; is a statement and expression.
See this : http://en.wikipedia.org/wiki/Expression_%28programming%29
http://en.wikipedia.org/wiki/Statement_%28programming%29