Which is the value of i in this "simple" initialization? - c++

I have a doubt about this code:
int i, x, z = 4, y = 1;
i = x = z += y++;
Which is the value of i? Can we know that value or not?

First of all, have you tested if this compiles at all?
If not, then why?
Unless you write some code that invokes UB, compiler, regarding basic syntax of the language, has most of the answers you'll ever need. Please test it yourself, and if it's still not clear, or behaves weirdly, then it's something worth asking.
In this case, it's valid, so let's go through it.
#include <iostream>
int main() {
int i, x, z = 4, y = 1;
i = x = z += y++;
std::cout << "i=" << i << std::endl;
}
I compiled, ran it, and here's the result:
$ g++ test.cpp -o test
$ ./test
i=5
So, what is actually going on in this line?
i = x = z += y++;
First of all, it's easier to understand when you add parentheses so it's perfectly obvious what is evaluated and when:
i = (x = (z += (y++)));
i is a result of assignment to x;
x is a result of addition assignment to z;
z is a result of z + (y post increment);
You can then work your way backwards through the list, and will arrive at the correct result:
y++ evaluates to simply y, because post increment affects only value of y, not the result of expression itself;
z is then z + y, which is 4 + 1, or 5;
intermediate expression becomes i = x = z; (or, form that's too obvious, i = (x = z);), and that means that i, just like x is 5.
Whatever you do, please don't actually write code like this, while it's easy to deconstruct, it's not something that is easy to understand at a first glance, and that, more often than not, causes confusion.

Can we know that value or not?
Yes.
Which is the value of i?
5
since you add y to i, where their values are 4 (since i gets assigned the value of z, which is 4) and 1 respectively.
y is incremented after z has been initialized. It's incremented in the following statement, as #john commented.
As #LightnessInOrbit commented, this is not good code. Forget about it and move on.

Yes the value of i is 5.
Just trace the code.
y++ post increement i,e first assign the value then increement so Y= 4. Next
z += y shorthand operation i,e.., z= z + y ,initially z=4 so 5 = 4+ 1 so Z=5
x = z i.e, x = 5 Next
i = x i.e, i = 5.

Related

Finding all the ordered pairs of integers lying on a line ax+by=c in better than O(n^2) time complexity [duplicate]

This question already has an answer here:
What's algorithm used to solve Linear Diophantine equation: ax + by = c
(1 answer)
Closed 5 years ago.
I am trying to write a code which can input 3 long int variables, a, b, c.
The code should find all integer (x,y) so that ax+by = c, but the input values can be up to 2*10^9. I'm not sure how to do this efficiently. My algorithm is O(n^2), which is really bad for such large inputs. How can I do it better? Here's my code-
typedef long int lint;
struct point
{
lint x, y;
};
int main()
{
lint a, b, c;
vector <point> points;
cin >> c >> a >> b;
for(lint x = 0; x < c; x++)
for(lint y = 0; y < c; y++)
{
point candidate;
if(a*x + b*y == c)
{
candidate.x = x;
candidate.y = y;
points.push_back(candidate);
break;
}
}
}
Seems like you can apply a tiny bit of really trivial math to solve for y for any given value of x. Starting from ax + by = c:
ax + by = c
by = c - ax
Assuming non-zero b1, we then get:
y = (c - ax) / b
With that in hand, we can generate our values of x in the loop, plug it into the equation above, and compute the matching value of y and check whether it's an integer. If so, add that (x, y) pair, and go on to the next value of x.
You could, of course, make the next step and figure out which values of x would result in the required y being an integer, but even without doing that we've moved from O(N2) to O(N), which is likely to be plenty to get the task done in a much more reasonable time frame.
Of course, if b is 0, then the by term is zero, so we have ax = c, which we can then turn into x = c/a, so we then just need to check that x is an integer, and if so all pairs of that x with any candidate value of y will yield the correct c.

Python My programming Lab

I have a problem doing one of the questions from my programming lab.
The question was like "Given the variables x, y, and z, each associated with an int, write a fragment of code that assigns the smallest of these to min."
And my work area looks like
if x < y and x < z:
x = min
if y < x and y < z:
y = min
if z < x and z < y:
z = min
When I turned in, the feedback said:
Remarks:
⇒ Unexpected identifiers: and
More Hints:
⇒ Solutions with your approach don't usually use: <
although I tried may ways to figure it out but none of them worked.
Plz help.
Thx.
For the first reply, the system said:
Remarks:
⇒ Unexpected identifiers: and
More Hints:
⇒ Solutions with your approach don't usually use: <
Problems Detected:
⇒ Exception occurred(, TypeError('unorderable types: int() < builtin_function_or_method()',), )
⇒ Exception occurred(, TypeError('unorderable types: int() < builtin_function_or_method()',), )
⇒ Exception occurred(, TypeError('unorderable types: int() < builtin_function_or_method()',), )
⇒ Exception occurred(, TypeError('unorderable types: int() < builtin_function_or_method()',), )
⇒ min does not contain the correct value
⇒ y was modified
⇒ z was modified
For the second reply, the system said:
Remarks:
⇒ Unexpected identifiers: and, def, minist
⇒ You have to use the min variable .
⇒ You should use an assignment operator (=) in this exercise.
More Hints:
⇒ You almost certainly should be using: =
⇒ You almost certainly should be using: min
⇒ I haven't yet seen a correct solution that uses: , (comma)
I see three issues with the code as you've shown it in the question.
The first is that your indentation is a bit messed up. You probably want all your if statements to be at the same level, with the corresponding assignment statements indented under each one:
if something:
foo = bar
if something_else:
foo = baz
# etc
You could also use elif statements instead of the second and third if, since you never expect to have more than one of the conditions true at the same time.
The second issue is that you're doing your assignment statements backwards. If you want to assign the value in a variable x to a new variable named min, you should put min on the left side and x on the right:
min = x
This is part of the reason you're getting lots of confusing errors. Before your code runs, min is the name of a builtin function (which I suspect you'll learn about later in your class). When you did x = min you were replacing the old x value with a reference to the function.
The last thing is a logic issue. Your comparisons are all using the < operator to test if one value is smaller than the others. The issue is what happens if two of the values are equal. If x and y have the same value, both x < y and y < x will be False. That's not very good for your code, and so you probably want to use the <= operator instead. It tests if the left side is less than or equal to the right side. With this version, if you're using elifs, you can actually do away with the last condition and just use else, since if neither x or y is less than or equal to the other values, z must be the smallest value by process of elimination.
Anyway, here's the code with all three issues fixed:
if x <= y and x <= z:
min = x
elif y <= x and y <= z:
min = y
else: # no "z <= x and z <= y" check needed here, will always be true if reached
min = z
Maybe the tab problem.
You can try this:
if x < y and x < z:
x = min
if y < x and y < z:
y = min
if z < x and z < y:
z = min
I make a sample:
#-*- coding:utf-8 -*-
def minist(x,y,z):
if x < y and x < z:
return x
if y < x and y < z:
return y
if z < x and z < y:
return z
x = 1
y = 2
z = 3
test = -1
test = minist(x,y,z)
print(test)
This sample will print 1.

Difference between += and =+ in C++

While programming in C++, I often confuse both "+=" and "=+", the former being the operator I actually mean. Visual Studio seems to accept both, yet they behave differently and is a source for a lot of my bugs. I know that a += b is semantically equivalent to a = a+b, but what does "=+" do?
=+ is really = + (assignment and the unary + operators).
In order to help you remember +=, remember that it does addition first, then assignment. Of course that depends on the actual implementation, but it should be for the primitives.
a =+ b means a = +b means a = b
if you see = the first , it means you re-declare your variable value ,
but if you face + the first it means that you order the compiler to increment the value of the variable , keep it in you mind
int x=20 ;
x=+10 ;
cout<< x <<endl ; // x = 10
x+=10 ;
cout<< x<<endl ; // x= 10+10 = 20
I may be remembering this wrong, but I think that in C, C++, and even Java (which has similar syntax to C and C++), =+ and += actually behave very similarly. The statement that =+ is assignment (equivalent to plain = operator), while += increases a variable's value by a certain amount, is INCORRECT.
x += y as well as x =+ y will BOTH have the same effect (that is, both of these will cause the new value of x to be the old value of x + y). The difference comes in when you have a slightly more complex expression.
z = (x += y) and z = (x =+ y) will have DIFFERENT outputs for the variable z.
Let's look at each one of these:
z = (x += y) will add y to x, and then set z to be the NEW value of x.
z = (x =+ y) will set z to be the OLD value of x, and then add y to x.
It's possible I got those 2 backwards, but I do remember reading somewhere before that the differences I describe here are the ACTUAL differences between those 2.

Is there a way to assign whichever value is not missing in a list of variables to another variable in a quicker way?

I am sitting with a situation and I can achieve the desired result but I was wondering if there is perhaps a quicker way to do it.
The long way would be something like this;
if ^missing(X) and nmiss(Y,Z) = 2 then Value = X;
else if ^missing(Y) and nmiss(X,Z) = 2 then Value = Y;
else if ^missing(Z) and nmiss(X,Y) = 2 then Value = Z;
This is fine for a few variables, but what happens when you have a list of many more variables. Is there a way to assign whichever value is not missing in a list of variables to another variable in a quicker way?
Something like;
if ^missing(in(X,Y,Z)) then Value = ^missing.value;
I know that the above code is incorrect, it is just a demonstration of my thought process.
Any help is greatly appreciated.
It isn't quite what you describe, but see the coalesce function: http://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a002518172.htm
value = coalesce(x, y, z);
This assigns the first non-missing value of x, y or z to value.
To do exactly like what you say you would do:
if n(of x y z) = 1 then value = coalesce(of x y z);
Of course you'd still have to assign values for non-n=1 values.
value = ifn(n(of x y z)=1,coalesce(of x y z), mean(of x y z));
Or something like that. In that particular case the mean(of x y z) would be equivalent to coalesce(of x y z), but if your solution when multiple exist would not work with just one, then you can plug it in there.

What's the output if output use ++x instead of x++? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Int y = 0
Int x = 5
y = x++
As compared to doing something like
Int y = 0
Int x = 5
y = ++x
Particularly, I'm asking how the position of the post increment generally affects the output
When the operator is before variable, it does (and supposed to when one writes own operators) perform an operation and then return result.
int x = 1 ;
int y = x++ ; // y = 1, x = 2
int z = ++x ; // x = 3, z = 3
I would suggest using temporary programs and outputs to see how things work.
Of course a good book is the best ;)
x++ increments x after the operation.
Int y = 0 Int x = 5 y = x++
Y would be equal to 5 while also setting x to equal 6.
Int y = 0 Int x = 5 y = ++x
Y would be equal to 6, X would also be equal to 6.
In the first case, y = x++, x is post-incremented. That is to say x is increased in value after its value is assigned to y.
y = 5 and x = 6.
In the second case, y = ++x, x is pre-incremented. x is increased in value before its value is assigned to y.
y = 6 and x = 6
If the prefix/postfix operator is part of an expression or function evaluation, it determines the order in which the variable is modified, either before the evaluation (prefix) or after the evaluation (postfix).
In this first case,y is assigned before x is incremented.
int y = 0;
int x = 5;
y = x++;
In this second case, x is incremented first, then y is assigned.
int y = 0;
int x = 5;
y = ++x;
Beware: if used in an array index on both sides of an equation, the behavior may be undefined.
pre-increment (++X): means that the value of X will be incremented before it gets assigned.
in your example, value of Y will be 6 because X gets incremented first (5+1) then gets assigned to Y.
post-increment (X++): means that the value of X will be incremented after it gets assigned.
in your example, value of Y will be 5 because X gets incremented after it is assigned to Y.
You can compare these as:
++X = in-place increment
X++ = increment happens in a temporary location (Temp=5+1) which gets assigned to X (X=Temp) after Y is set to its current value (5).
Y = X++ can be represented as:
> Temp = X+1
> Y = X
> X = Temp