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
Related
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.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
So, im new to coding and trying to get into c++. I was trying to get through the second problem on Project Euler and thought i had a good grasp on how to approach it. Hours later, i gave up and decided to look it up.
int x = 0;
int y = 1;
int z = x + y;
int sumeven = 0;
while (z < 4000000)
{
x = y;
y = z;
z = x + y;
if (z % 2 == 0)
{
sumeven += z;
}
}
cout << sumeven;
thr problem im having is with the
x=y; y=z; z=x+y;
everything else i understand.
can someone explain this to me please. Im not sure how i would have known to do this without looking it up.
Z is always being set to be the sum of the previous two numbers, where x is "2 numbers ago" and y is "the previous number".
So, after z is calculated, the next iteration has to be set up. We now want "2 numbers ago" to be what had been y in this iteration:
x = y;
And we want "the previous number" to be the z that was just calculated:
y = z;
Now we calculate the new z:
z = x + y;
This example tries to calculate summation of even numbers of Fibonacci sequence, each number in Fibonacci sequence is the result of adding last two numbers. So here is what's happening :
Start from 0 : int x = 0; \\x is 0 now
The second number is 1 : int y = 1; \\y is 1 now
Add them to get 3d number : int z = x + y; \\z is 1 now as it's result of adding 0 and 1
Copy y to x : x = y; \\so x is 1 now, as you can see we are advancing our variables in Fibonacci sequence, It means x is the second number of sequence now
Copy z to y : y = z; \\as I said, we are advancing in sequence so now y is 3d element of sequence (it was 2nd before) and it's value is 1 now
Calculate z base on last two elements (x and y) : z = x + y; \\ so here z would be our 4th element which of course it's calculated by last two so it's value would be 2 as x and y were both 1
Test if it's an even number : if (z % 2 == 0)
If it is, add it to our summation variable : sumeven += z;
Go to step 4
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.
int x, y; // x is a non-negative integer
p = 0;
while (x > 0)
{
if ( x % 2 == 1 )
p = p + y;
y = y*2;
x = x/2;
}
// p == a*b here
I understand that this loop finds the product of 'a' and 'b' using the algebra:
a * b = (1/2)a * 2b
but I don't understand the code:
if ( x % 2 == 1 )
p = p + y;
I was hoping someone could explain why 'p' is assigned 'p + y' on odd values of x.
while (x > 0) {
if (x % 2 == 1)
p = p + y;
y = y*2;
x = x/2;
}
imagine x = 4, y = 5
iterations:
x is even, y = 10, x = 2 (i.e. x can be divided, y should be doubled)
x is even, y = 20, x = 1
x is odd, p = 20, y = 40, x = 0 (i.e. x can not be divided anymore, y should be added to p)
x > 0 is false, loop ends
p = 4 * y
now imagine x is odd at the beginning, let's say x = 5, y = 2:
x is odd, p = 2, y = 4, x = 2
(5/2 = 2.5, new value of x will be rounded down, y should be added BEFORE it is doubled)
x is even, y = 8, x = 1
x is odd, p = 10, y = 16, x = 0
p = y + 4*y
that first y is the reason, adding it to the result before it is doubled (1 * y) is in this case equivalent to 0.5 * (2 * y)
Because these are integers, a / 2 will be an integer. If a is odd, that integer has been rounded down, and you’re missing one-half b in the next iteration of the loop, i.e. one whole b in the current iteration of the loop (since b [y] is doubled each time).
If x is odd, x = x/2 will set x to 0.5 less than x/2 (because integer division rounds it down). p needs to be adjusted to allow for that.
Think of multiplication as repeated addition, x*y is adding y together x times. It is also the same as adding 2*y together x/2 times. Conceptually it is somewhat unclear what it means if x is odd. For example, if x=5 and y=3, what does it mean to add 2.5 times? The code notices when x is odd, adds y in, then does the y=y*2 and x=x/2. When x is odd, this throws away the .5 part. So in this example, you add y one time, then x becomes 2 (not 2.5) because integer division throws away the fraction.
At the end of each loop, you will see that the product of the original x and y is equal to p + x*y for the current values of p, x, and y. The loop iterates until x is 0, and the result is entirely in p.
It also helps to see what is going on if you make a table and update it each time through the loop. These are the values at the start of each iteration:
x | y | p
----------
5 | 3 | 0
2 | 6 | 3
1 | 12 | 3
0 | 24 | 15
This works by observing that (for example) y * 10 = y * 8 + y * 2.
It's pretty much like doing multiplication on paper in school. For example, to multiply 14 x 21, we multiply one digit at a time (and shift left a place where needed) so we add 1x14 + 2 x 14 (shifted left one digit).
14
x 21
----
14
280
Here, we're doing pretty much the same thing, but working in binary instead of decimal. The right shifting has nothing to do with the numbers being odd, and everything to do with simply finding which bits in the number are set.
As we shift one operand right to find whether a bit is set, we also shift the other operand left, just like we add zeros to shift numbers left when doing arithmetic on paper in decimal.
So, viewing things in binary, we end up with something like:
101101
x 11010
--------
1011010
+ 101101000
+ 1011010000
If we wanted to, instead of shifting the operand right, we could just shift the mask left so instead of repeatedly anding with 1, we'd and with 1, then with 2, then with 4, and so on (in fact, it would probably make a lot more sense that way). For better or worse, however, in assembly language (where this sort of thing is normally done) it's usually a little easier to shift the operand and use a constant for the mask than load the mask in a register and shift it when needed.
You should rewrite x as 2*b+1 (assuming x is odd). Then
x*y = (2*b+1)*y = (2*b)*y + y = b*(2*y) + y = (x/2)*(2*y) + y
where (x/2) is meant to be the integer division. With the operation rewritten this way, you see the x/2, the 2y and the +y appear.
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.
I want to create a function that finds the product of two integers by using addition that can handle negatives and positives both.
This is the code I have so far...
getting crazy numbers as results ..I am a noob..Thank you
double multi(double n1, n2)
{
double answer(0), i=0;
do
{
answer += n1; i++;
} while (i < n2);
return answer;
}
You could start by using integers instead of doubles and actually pass them both as parameters....
int multi( int x, int y )
{
int answer = 0;
// stuff goes here...
return answer;
}
I suspect this is homework, so I'm not going to give you code verbatim...
But consider that if one value is negative, the result will be negated relative to the answer if that same value was positive. Effectively if you are going to add x and do it y times, then you can flip the sign of both x and y if y is negative. That negates the answer and gives you a positive y to loop over.
An optimization would be to check which of the two values is larger, and use the smaller one as the loop variable.
..yes this is hmwk..but I'm sorry I don't understand you mean..
Imagine you have two integers X and Y. If Y is positive, it's easy to see:
X * Y = (X + X + X + X + ...)
Now, what about if Y is negative? I'm going to use -Y to denote that:
X * -Y = -(X * Y)
= -(X + X + X + X + ...)
= (-X - X - X - X - ...)
= ((-X) + (-X) + (-X) + (-X) + ...)
So, if Y is positive I add together Y copies of X. If Y is negative I add together -Y copies of -X.
If this still doesn't help, then I suggest you sit down and think about it for a while.