unexpected result while evaluating the operators - java

I have below code and it gives an unexpected result. To my understanding, the result should be 6 but its 1. Can someone help me how to get it?
int j = 0;
int i1 = j*5+ ++j;
System.out.println("j =" + j);
System.out.println("i1 =" + i1);

The difference between getting 6 and getting 1 is whether you think j*5 will be evaluated first or ++j will be evaluated first. The rule in Java is that subexpressions are evaluated in the order they appear in the expression if the order is not forced by dependencies. Here, j*5 appears first in the expression, so it is evaluated first. That gives the 1 result.

You have something like the code below:
int j = 0;
int i1 = j*5+ ++j;
System.out.println("j =" + j);
System.out.println("i1 =" + i1);
You need to edit your code to this:
int j = 0;
int i1 = ++j*5 + j;
System.out.println("j =" + j);
System.out.println("i1 =" + i1);
Your final output for "i1 =" + i1) will be 6.
The issue is that in your first code sample you are not incrementing J before you multiply it by 5 so you're only increasing it by +1 because you don't actually increment j until you've multiplied 0 * 5. (0 * 5) + 1 = 1. What I did was simply increment j (in prefix form) so that it increments by 1, and now you're multiplying (1 * 5) + 1.

Related

Magic square code loop

This is the code for a method which creates a magic square. n is the length of the square. It has to look like:
static int[][] magicSquare(int n) {
int[][] square=new int[n][n];
I don't understand this k=(k+1)%n; especially, why is it %n ?? Doesn´t that put k to 1 every loop again?
for (int i=0; i<n; i++){
in k=i;
for (int j=0; j<n; j++){
square[i][j]=k+1;
k=(k+1)%n;
1 2 3 4
2 3 4 1
3 4 1 2
4 1 2 3
The % in Java is used for modular division. Whenever the operator is applied the right-hand operand will be subtracted as many times as it can from the left-hand operand and what's left will be the output. You can easily check it by dividing the left-hand operand by the right-hand operand and take the leftover as an integer. In the case of a%b it will be like
a - (a/b)*b.
here are some examples:
10 % 4 = 2 // 2*4 = 8 + 2 = 10
10 % 5 = 0 // 2*5 = 10 + 0 = 10
0 % 4 = 0 // result here is 0 thus 0*4 = 0 + 0 = 0
// if you try to extract 4 from 0, you will not succeed and what's left will be returned (which was originally 0 and it's still 0)...
In your case:
k = (k + 1) % n;
is assuring that the value of k will never exceed 4, thus if it is dividable by 4 then it will be divided and the leftover will be written there. In the case when k is exactly 4 you will have the value of 0 written down into k but since you are always adding k + 1 it is writing the value of 1.
For beginners I do recommend to print the values you are interested in and observe how do the data migrate. Here I've added some printlns for you just to get the idea. Run the code and test it yourself. I do believe the things are going to be a bit cleaner.
public static void main(String[] args) {
int n = 4;
int[][] square = new int[n][n];
System.out.println("--------------");
for (int i = 0; i < n; i++) {
int k = i;
System.out.println("Filling magic cube line " + (i + 1) + ". The k variable will start from " + i + "."); // i initial value is 0 so we add 1 to it just to get the proper line number.
for (int j = 0; j < n; j++) {
System.out.println("Filling array index [" + i + "][" + j + "] = " + (k + 1)); // array indexes start from 0 aways and end at array.length - 1, so in case of n = 4, last index in array is 3.
square[i][j] = k + 1; // add 1 to k so the value will be normalized (no 0 entry and last entry should be equal to n).
k = (k + 1) % n; // reset k if it exceeds n value.
}
System.out.println("--------------");
}
Arrays.stream(square).forEach(innerArray -> {
Arrays.stream(innerArray).forEach(System.out::print);
System.out.println();
});
}
You could always play around and refactor the code as follows:
public static void main(String[] args) {
int n = 4;
int[][] square = new int[n][n];
System.out.println("--------------");
for (int i = 1; i <= n; i++) {
int k = i;
System.out.println("Filling magic cube line " + i + ". The k variable will start from " + i + ".");
for (int j = 0; j < n; j++) {
System.out.println("Filling array index [" + (i - 1) + "][" + (j - 1) + "] = " + k); // array indexes start from 0 aways and end at array.length - 1, so in case of n = 4, last index in array is 3. Subtract both i and j with 1 to get the proper array indexes.
square[i - 1][j - 1] = k;
k = (k + 1) % n; // reset k if it exceeds n value.
}
System.out.println("--------------");
}
Arrays.stream(square).forEach(innerArray -> {
Arrays.stream(innerArray).forEach(System.out::print);
System.out.println();
});
}
Remember that the array's indexing starts from 0 and ends at length - 1. In the case of 4, the first index is 0 and the last one is 3. Here is the diff of two implementations, try to see how does the indexes and values depends both on the control variables i and j.
https://www.diffchecker.com/x5lIWi4A
In the first case i and j both start from 0 and are growing till they it's values are both less than n, and in the second example they start from 1 and are growing till they are equal to n. I hope it's getting clearer now. Cheers

Why i += i + a[i++] + a[i++] + a[i++] results in 8?

I am totally lost why I get these results:
int i = 1;
int[] a = new int[6];
a[0] = 0;
a[1] = 1;
a[2] = 2;
a[3] = 3;
a[4] = 4;
a[5] = 5;
i += i + a[i++] + a[i++];
//i is 5
i = 1;
i += i + a[i++] + a[i++] + a[i++];
// i is 8
I (wrongly) thought that there are these options:
i = i(=1) + a[i++] + etc - meaning that i = 1 is cached and not
changed then. Expression evaluation order is exactly from left to
right, I guess (?!).
i is increased, which results (for first example) in i = i(=3) + a[1] + a[2] now i = 3 and written to leftmost i
value from rightmost a[THIS_VALUE] is substituted into leftmost i, and last increment is never made.
But actual results leave me with no clue...
i += i + a[i++] + a[i++];
adds the original value of i to the value of the expression i + a[i++] + a[i++] and assigns the result to i.
It's equivalent to
i = i + i + a[i++] + a[i++];
1 + 1 + a[1] + a[2] = 1 + 1 + 1 + 2 = 5
Then you assign 1 to i and calculate:
i += i + a[i++] + a[i++] + a[i++];
which is equivalent to
i = i + i + a[i++] + a[i++] + a[i++];
1 + 1 + a[1] + a[2] + a[3] = 1 + 1 + 1 + 2 + 3 = 8
The important thing to note is that each a[i++] increments i, but accesses the element of a at the index of the previous value of i (i.e. the value prior to the increment).
Therefore the first a[i++] returns a[1] (even though i is incremented to 2), the second a[i++] returns a[2] (even though i is incremented to 3) and the third a[i++] returns a[3] (even though i is incremented to 4).
This important to notice differences between i++ and ++i, when you use i++ it use i value to calculate the operation and then increment i, but when you are using ++i it increment i and the calculate the operation.
it also worth mentioning that i+=X is equal to i = i + X.
So
i += i + a[i++] + a[i++];
is equal to
i = i + i + a[i++] + a[i++]
for i = 1 it is
i = 1 + 1 + a[1] + a[2]
which with your initialisation it will be :
i = 1 + 1 + 1 + 2
and thats how you get i = 5. and same for next line.
Its quite easy acutally, your using post increment. Post increment increments the value after the expression was executed, versus pre which increments before the expression is executed. So i += i + a[i++] + a[i++] + a[i++];, is 1 += 1 + 1 + 2 + 3, the first access, uses 1, then increment, next access uses two then increment then last access uses three.

Counting number of comparisons in code

for(int i = 0; i < N * N; i = i + 1)
for(int j = 1; j < i + 1; j = j + 1)
junk = junk + 1;
I need to determine the relationship between the number of < operations executed and N. I should give an exact answer, such as 27N + 18.
Any help is appreciated! Thanks
For the first loop, as you can see i starts from 0 and goes to N^2 -1
1) That means N^2 + 1 times.
For every i, inner loop starts with 1 goes to N^2
2) 1 + 2 + 3 ... (N^2) = N^2 * (N^2 +1 ) / 2 = (N^4 + N^2) / 2
That means, operator "<" executed sum of 1 and 2.
N^2 + 1 + (N^4 + N^2) / 2 = (N^4 + 3N^2 + 2) / 2
= **(N^2 + 2) (N^2 + 1) / 2**

while nested in for loop. How does the decrement operator work?

I couldn't figure out how the decrement operator (e--)
works in code below, so i wrote the other class below it
to get the same result. I want to know how the decrement operator
achieves that result in the Power class. - Newbie.
int result, e;
for(int i=0; i < 10; i++) {
result = 1;
e = i;
while(e > 0) {
result *= 2;
e--;
}
System.out.println("2 to the " + i +
" power is " + result);
}
Code written to achieve same result
int result = 1;
for(int i=0; i < 10; i++) {
if (i > 0) {
result*=2;
}
System.out.println("2 to the " + i +
" power is " + result);
}
So the first example is resetting result for each iteration of the main for loop, so it needs to recalculate from scratch each time, where as the second example is keeping the previous computed value. The if in the second example is not needed is it.
The decrement operator modifies the variable on which it's called. So e-- is effectively e = e - 1 (except the overall result of the expression is different, see below).
This code:
result = 1;
e = i;
while(e > 0) {
result *= 2;
e--;
}
starts with result = 1 and then loops for i iterations doubling the value in result. Equivalent code using for which you seem more comfortable with:
result = 1;
for (e = 0; e < i; e++) {
result *= 2;
}
There are two forms of the decrement (and increment) operator: Prefix and postfix, depending on whether the operator is before (prefix) or after (postfix) its operand. Either could be used in the code you were asking about, because the only difference is the result of the expression.
Prefix: Suppose we have x = 5. The expression --x has the value 4: First we decrement x, then we take its new value as the result of the expression.
Postfix: Suppose we had x = 5 (again). The expression x-- has the value 5, with x ending up containing 4: First we grab the current value of x as the result of the expression, then we decrement it (because the -- is after x).
int x, r;
x = 5;
r = --x; // Prefix
System.out.println("r = " + r + ", x = " + x); // "r = 4, x = 4"
x = 5;
r = x--; // Postfix
System.out.println("r = " + r + ", x = " + x); // "r = 5, x = 4"
i figure out that by placing a System.out.println(e) i could "see" the variable "e" behavior in order to make sense of the decrement.
class Power {
public static void main(String args[]) {
int e;
int result;
for(int i=0; i < 10; i++) {
result =1 ;
e = i;
while(e > 0) {
System.out.println(e); // not part of the original program
result *= 2 ;
e--;
System.out.println(e); // not part of the original program
}
//System.out.println("2 to the " + i +
//" power is " + result);
}
This is the output:
C:\Users\enrique\Desktop\Hello.java>java Power: 1, 0, 2, 1, 1, 0, 3
e = 1(iteration 1), 2^1, e (1) decremented to 0, e = 2 (iteration 2), 2^2, e(2) decremented to 1, e = 1 re-enter The while but is ignored as 2^1 is already registered, e (1) decremented to 0, e = 3 (iteration 3), 2^3…

++i+i++ evaluation

Confusion rose because of this post. The author updated his post, and the result became clear.
Conclusion: Java evaluates expressions from left to right
Closed!
As evaluation of expression is done from right to left the following code should store 5 in j:
int i=2;
int j=++i+i++;
System.out.println(j);
But I get 6 as the output, which forces me to re-think the right to left evaluation idea. Kindly explain the theory here.
You get 6 because it's 3 + 3:
the first OP is ++i which increments first (to 3) then that value is used
next OP is +i which adds 3 again
last OP ++ doesn't take part in the addition, but it increments i after using it
Your assumption is false. Here's what the documentation says :
All binary operators except for the assignment operators are evaluated
from left to right
So
++i+i++
is equivalent to
(++i)+(i++)
where ++i is evaluated first.
This gives
3+3
which is 6 (and i has value 4 after this).
int i = 2;
int j = ++i + i++;
is the same as
int i = 2;
// This part is from ++i
i = i + 1;
int left = i; // 3
// This part is from i++
int right = i; // 3
i = i + 1;
int j = left + right; // 3 + 3 = 6
If instead you'd done:
int i = 2;
int j = i++ + ++i;
that would be equivalent to:
int i = 2;
// This part is from i++
int left = i; // 2
i = i + 1;
// This part is from ++i
i = i + 1;
int right = i; // 4
int j = left + right; // 2 + 4 = 6
So the sum is the same, but the terms being summed are different.
The first ++ increments i. The + adds i to itself. i is 3.
Where'd you get the idea that it is right-to-left? It is left-to-right.
What are the rules for evaluation order in Java?
This how it works, since unary operators have more precedance than binary:
int i=2;
int j =(++i)+(i++);
^^^ ^^^
3 +(i++) //The value of i is now 3.
^^^ ^^^
3 + 3 //The value of i is incremented after it is assigned.
When evaluating an expression such as a+b, before you can add 'b' to 'a', you need to know what 'a' is. In this case, a is ++i, which is 3, and b is i++ which is 3. Evaluating right-to-left gives 3 + 3 = 6
In Java and C#, the evaluation of subexpressions will be done left to right:
int j=++i + i++;
contains the following two subexpressions ++i and i++. These subexpressions will be evaluated in this order so this will translate into:
int j= 3 + 3;
As in Java and C#, the ++i will be executed returning 3 but i will be changed to 3 before the second i++. The second will return the current value of i which is 3 now and after i++ the value of i will be 4.
In C++ this would be undefined.
And in real-world, you do not want to type this code (except for code golfing)

Categories

Resources