weird operator precedence and assignment behavior in borland turboC++ - operators

I have to use borland TurboC++ for C programming in my college.
They say our examination board recommends it. I have to use it..
The problem is that they gave this operator precedence related question:
int a=10,b=20,result;
result1 = ++a + b-- - a++ * b++ + a * ++b;
printf("result=%d",);
printf("\n a=%d",a);
printf("\n b=%d",b);
Other compilers like gcc can't perform this operation. But turbo C can and gives us:
result=32
a=12
b=21
I made mistake in my test. My teacher tried to explain what's going on. But I am not convinced. Is it some kind of weird behavior of turbo C or in older days it used to be totally fine with all compilers. If so, what are the steps to understand what is going on and how to understand.

To solve these kind of problem, turbo-c do it in manner as follows :
1) Consider the initial value of variables used.
a=10
b=20
2) Count all the pre-increment and decrements for each variable and store all post on stack separate for each variable.
for variable a
pre increment = 1 therefore change the value of a to 11
post = 1 stored to stack
for variable b
pre increment = 1 therefore change the value of b to 21
post = 2 stored to stack
3) Now replace all the pre and post with the current value of a and b
result = 11 + 21 - 11 * 21 + 11 * 21 ;
result = 11 + 21;
result = 32;
4) lastly pop the stack and perform the operation on the variable.
a = 12
b = 21
This the only way to solve this problem. You can check the procedure with any question of same kind. The result will came out same. g++ fails to solve because it probably cannot resolve the variable in the same way thus the precedence error came in picture. It might probably fail with ++ + and -- - because it cannot understand the increment or decrements operator and forms ambiguous trees.

Related

Given no modulus or if even/odd function, how would one check for an odd or even number?

I have recently sat a computing exam in university in which we were never taught beforehand about the modulus function or any other check for odd/even function and we have no access to external documentation except our previous lecture notes. Is it possible to do this without these and how?
Bitwise AND (&)
Extract the last bit of the number using the bitwise AND operator. If the last bit is 1, then it's odd, else it's even. This is the simplest and most efficient way of testing it. Examples in some languages:
C / C++ / C#
bool is_even(int value) {
return (value & 1) == 0;
}
Java
public static boolean is_even(int value) {
return (value & 1) == 0;
}
Python
def is_even(value):
return (value & 1) == 0
I assume this is only for integer numbers as the concept of odd/even eludes me for floating point values.
For these integer numbers, the check of the Least Significant Bit (LSB) as proposed by Rotem is the most straightforward method, but there are many other ways to accomplish that.
For example, you could use the integer division operation as a test. This is one of the most basic operation which is implemented in virtually every platform. The result of an integer division is always another integer. For example:
>> x = int64( 13 ) ;
>> x / 2
ans =
7
Here I cast the value 13 as a int64 to make sure MATLAB treats the number as an integer instead of double data type.
Also here the result is actually rounded towards infinity to the next integral value. This is MATLAB specific implementation, other platform might round down but it does not matter for us as the only behavior we look for is the rounding, whichever way it goes. The rounding allow us to define the following behavior:
If a number is even: Dividing it by 2 will produce an exact result, such that if we multiply this result by 2, we obtain the original number.
If a number is odd: Dividing it by 2 will result in a rounded result, such that multiplying it by 2 will yield a different number than the original input.
Now you have the logic worked out, the code is pretty straightforward:
%% sample input
x = int64(42) ;
y = int64(43) ;
%% define the checking function
% uses only multiplication and division operator, no high level function
is_even = #(x) int64(x) == (int64(x)/2)*2 ;
And obvisouly, this will yield:
>> is_even(x)
ans =
1
>> is_even(y)
ans =
0
I found out from a fellow student how to solve this simplistically with maths instead of functions.
Using (-1)^n :
If n is odd then the outcome is -1
If n is even then the outcome is 1
This is some pretty out-of-the-box thinking, but it would be the only way to solve this without previous knowledge of complex functions including mod.

I heard that Haskell variables are immutable but i am able to reassign and update variable values [duplicate]

This question already has an answer here:
Haskell: What is immutable data?
(1 answer)
Closed 4 years ago.
I heard that Haskell variables are immutable but i am able to reassign and update variable values
First, note that GHCi syntax is not quite the same as Haskell source-file syntax. In particular, x = 3 actually used to be illegal as such:
GHCi, version 7.10.2: http://www.haskell.org/ghc/ :? for help
Prelude> x = 3
<interactive>:2:3: parse error on input ‘=’
Newer versions have made this possible by simply rewriting any such expression to let x = 3, which has always been ok:
GHCi, version 7.10.2: http://www.haskell.org/ghc/ :? for help
Prelude> let x = 3
Prelude> x
3
By contrast, in a Haskell source file, let x = 3 has never been legal by itself. This only works in a particular environment, namely a monadic do block.
main :: IO ()
main = do
let x = 3
print x
3
And the GHCi prompt by design actually works like the lines in a do block, so let's in the following discuss that. Note that I can also write
main = do
let x = 1
let x = 3
print x
3
And that's basically what's also going on in your GHCi session. However, as the others have remarked, this is not mutation but shadowing. To understand how this works, note that the above is essentially a shorthand way of writing
main =
let x = 1
in let x = 3
in print x
So, you have two nested scopes. When you look up a variable in some expression, Haskell always picks the “nearest one”, i.e. in the inner scope:
main =
let x = 1
┌──
in│let x = 3
│in print x
└─
The outer x isn't touched at all, it's basically unrelated to anything going on in the inner scope. The compiler will actually warn you about this, if asked if there's anything fishy in your file:
$ ghc -Wall wtmpf-file16485.hs
[1 of 1] Compiling Main ( wtmpf-file16485.hs, wtmpf-file16485.o )
wtmpf-file16485.hs:3:8: warning: [-Wunused-local-binds]
Defined but not used: ‘x’
|
3 | let x = 1
| ^
wtmpf-file16485.hs:3:12: warning: [-Wtype-defaults]
• Defaulting the following constraint to type ‘Integer’
Num p0 arising from the literal ‘3’
• In the expression: 3
In an equation for ‘x’: x = 3
In the expression:
do let x = 1
let x = 3
print x
|
3 | let x = 1
| ^
wtmpf-file16485.hs:4:8: warning: [-Wname-shadowing]
This binding for ‘x’ shadows the existing binding
bound at wtmpf-file16485.hs:3:8
|
4 | let x = 3
| ^
There: the second definition simply introduces a new, more local variable which also happens to be called x, but is unrelated to the outer variable. I.e. we might as well rename them:
main = do
let xOuter = 1
let xInner = 3
print xInner
A consequence of all this is that a variable that's “mutated” in this way has no influence on other functions which use the original variable. Example:
GHCi, version 8.2.1: http://www.haskell.org/ghc/ :? for help
Loaded GHCi configuration from /home/sagemuej/.ghci
Loaded GHCi configuration from /home/sagemuej/.ghc/ghci.conf
Prelude> let x = 1
Prelude> let info = putStrLn ("x is ="++show x++" right now")
Prelude> x = 3
Prelude> info
x is =1 right now
Another consequence is that “updates” which try to use the old value behave in a funny way:
Prelude> let s = "World"
Prelude> s = "Hello"++s
Prelude> s
"HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHell^C
Here, the new binding does not just prepend "Hello" to the old s="World". Instead, it prepends "Hello" to its own result value, which is in turn defined by "Hello" prepended to... and so on, recursively.
You're shadowing, not mutating.

minimize/1 is not rearranging the order of solutions

For Colombia's Observatorio Fiscal[1], I am coding a simple tax minimization problem, using CLP(R) (in SWI-Prolog). I want to use minimize/1 to find the least solution first. It is instead listing the bigger solution first. Here is the code:
:- use_module(library(clpr)).
deduction(_,3). % Anyone can take the standard deduction.
deduction(Who,D) :- itemizedDeduction(Who,D). % Or they can itemize.
income(joe,10). % Joe makes $10 a year.
itemizedDeduction(joe,4). % He can deduct more if he itemizes.
taxableIncome(Who,TI) :-
deduction(Who,D),
income(Who,I),
TI is I - D,
minimize(TI).
Here is what an interactive session looks like:
?- taxableIncome(joe,N).
N = 7 ;
N = 6 ;
false.
If I switch the word "minimize" to "maximize" it behaves identically. If I include no minimize or maximize clause, it doesn't look for a third solution, but otherwise it behaves the same:
?- taxableIncome(joe,N).
N = 7 ;
N = 6.
[1] The Observatorio Fiscal is a new organization that aims to model the Colombian economy, in order to anticipate the effects of changes in the law, similar to what the Congressional Budget Office or the Tax Policy Center do in the United States.
First, let's add the following definition to the program:
:- op(950,fy, *).
*_.
Using (*)/1, we can generalize away individual goals in the program.
For example, let us generalize away the minimize/1 goal by placing * in front:
taxableIncome(Who,TI) :-
deduction(Who,D),
income(Who,I),
TI #= I - D,
* minimize(TI).
We now get:
?- taxableIncome(X, Y).
X = joe,
Y = 7 ;
X = joe,
Y = 6.
This shows that CLP(R) in fact has nothing to do with this issue! These answers show that everything is already instantiated at the time minimize/1 is called, so there is nothing left to minimize.
To truly benefit from minimize/1, you must express the task in the form of CLP(R)—or better: CLP(Q)— constraints, then apply minimize/1 on a constrained expression.
Note also that in SWI-Prolog, both CLP(R) and CLP(Q) have elementary mistakes, and you cannot trust their results.
Per Mat's response, I rewrote the program expressing the constraints using CLP. The tricky bit was that I had to first collect all (both) possible values for deduction, then convert those values into a CLP domain. I couldn't get that conversion to work in CLP(R), but I could in CLP(FD):
:- use_module(library(clpfd)).
deduction(_,3). % Anyone can take the same standard deduction.
deduction(Who,D) :- % Or they can itemize.
itemizedDeduction(Who,D).
income(joe,10).
itemizedDeduction(joe,4).
listToDomain([Elt],Elt).
listToDomain([Elt|MoreElts],Elt \/ MoreDom) :-
MoreElts \= []
, listToDomain(MoreElts,MoreDom).
taxableIncome(Who,TI) :-
income(Who,I)
, findall(D,deduction(Who,D),DList)
, listToDomain(DList,DDomain)
% Next are the CLP constraints.
, DD in DDomain
, TI #= I-DD
, labeling([min(TI)],[TI]).

How to test a bit in a decimal number

I have a set of decimal numbers. I need to check if a specific bit is set in each of them. If the bit is set, I need to return 1, otherwise return 0.
I am looking for a simple and fast way to do that.
Say, for example, I am checking if the third bit is set. I can do (number AND (2^2)), it will return 4 if the bit is set, otherwise it will return 0. How do I make it to return 1 instead of 4?
Thank you!
if ((number AND (2^bitnumber) <> 0) then return 1 else return 0 end if
If you can change your return type to boolean then this is more elegant
return ((number AND (2^bitnumber)) <> 0)
While the division solution is a simple one, I would think a bit-shift operation would be more efficient. You'd have to test it to be sure, though. For instance, if you are using 1 based bit indexes, you could do this:
Dim oneOrZero As Integer = (k And 2 ^ (n - 1)) >> (n - 1)
(Where k is the number and n is the bit index). Of, if you are using 0 based bit indexes, you could just do this:
Dim oneOrZero As Integer = (k And 2 ^ n) >> n
Sorry, guys, I am too slow today.
To test a bit number "n" in a decimal number "k":
(k AND 2^(n-1))/(2^(n-1))
will return 1 if the bit is set, otherwise will return 0.
=====================================================
Hi again, guys!
I compared the performance of the three proposed solutions with zero-based indexes, and here are the results:
"bit-shift solution" - 8.31 seconds
"if...then solution" - 8.44 seconds
"division solution" - 9.41 seconds
The times are average of the four consecutive runs.
Surprisingly for me, the second solution outperformed the third one.
However, after I modified the "division solution" this way:
p = 2 ^ n : oneOrZero = (k And p) / p
it started to run in 7.48 seconds.
So, this is the fastest of the proposed solutions (despite of what Keith says :-).
Thanks everybody for the help!
I really don't know if it can help anyone more than the above, but, here we go.
When I need to fast check a bit in number I compare the decimal-value of this bit directly.
I mean, if I would need to see of the 6th bit is on (32), I check its decimal value, like this:
if x and 32 = 32 then "the bit is ON"
Try for instance check 38 with 32, 4 and 2... and the other bits.
You will see only the actual bits turned on.
I hope it can help.
Yes! Simply use a bit mask. I enumerate the bits, then AND the number with the bit value. Very little math on the PC side as it uses lookup tables instead. The AND basically shuts off all the other bits except the one you are interested in. Then you check it against itself to see if it's on/off.
Enum validate
bit1 = 1
bit2 = 2
bit3 = 4
bit4 = 8
bit5 = 16
bit6 = 32
bit7 = 64
bit8 = 128
End Enum
If num And validate.bit3 = validate.bit3 Then true

What will be the value of i in the following pseudocode?

I got this question in a programming test. Do you think this question is even correct? Look at the answer choices. (2^x means 2 raised to x)
Consider the following pseudocode.
x := 1;
i := 1;
while (x >= 1000)
begin
x := 2^x;
i := i + 1;
end;
What is the value of i at the end of the pseudocode?
a) 4
b) 5
c) 6
d) 7
e) 8
I am sure that the value of i will 1. I told the examiner of the discrepancy and he advised me the leave the question unanswered if I felt it was incorrect. What else could I have done?
1
X < 1000, so it doesn't enter the while.
Or there is an error in the Question (and X should be <= 1000 and not >=1000)
If it's <= 1000 it should be 5:
2 - 4 - 16 - 65K
2 - 3 - 4 - 5
This question tests two things:
can you read code
can you communicate / interact
Since you asked about the discrepancy, you showed 1. to be true. I'm not so sure if you passed 2, it depends too much on the situation / expectations.
I believe I would have left a note on the answer sheet stating 'none of the given'.
Not an easy situation!
As written, the answer would be 1.
Had the test on the while been reversed (i.e. x < 1000), then the series is:
At the end of each loop iteration
i = 2, x = 2
i = 3, x = 2^2 = 4
i = 4, x = 2^4 = 16
i = 5, x = 2^16 = 65,536
So i would be 5
If I where you, I would say that it is none of the above and basically say that since x is less than 1000 when the while loop starts, the value of i is never modified. I think that it is a bad thing to leave blank answers in a quiz, it is always better to write something which you think is relevant. If you think that there is a mistake, you can always state an assumption before stating your answer, so in this case you can either say that the while loop never works, or else, you explicitly state an assumption, in this case, it would be something like "Assuming that there is a mistake in the question, and that "while (x >= 1000)" should in fact be "while (x <= 1000)"...
Then, you proceed with your working.