Question about post-increment operator - java

Why does the following code
int i = 1;
System.out.print(i += i++);
System.out.print(i);
output 2 two times instead of 3 for the 2nd print?
Could somebody please shed some light on it?
Thanks.

If you realise that a++ works as follows (pseudocode):
func ++(ref a)
{
int b=a;
a=a+1;
return b;
}
then it all makes sense.

It may seems like i should be 3 in the end.
However, if you look into the statement more closely
i += (i++)
is equal to
i = ( i + (i++) )
which is, in this case, 1+1.
The side effect of i++ is i=i+1=1+1=2 as you may have expected, however, the value of i is override after the assignment.

I don't know the Java bytecode syntax very well yet but according to me at bytecode level your code would look something like this :
int i = 1; // iconst_1: variables { }, stack {1}
// istore_1: variables {1}, stack { }
i += i++; // iload_1: variables {1}, stack {1}
// iinc 1, 1: variables {2}, stack {1}
// iadd: variables {2}, stack {2} ...Note that here 1 gets added to the value on stack
// istore_1: variables {2}, stack {2} ...Here the variable value will overwrite the stack value
I think this explains the output you are getting pretty well. :-)
Experts, please correct me if I am wrong...

I don't think this is an issue with not knowing how the postfix unary operator (expr++) works. It is the order in which the statements are evaluated that is creating the confusion.
int i = 1;
System.out.println(i += i++); // Output: 2
So the last statement is the same as the following two statements in this order:
i++; // i is now 2 for the rest of this statement and the program
i = 1 + 1; // i is assigned again
So the postfix operator is evaluated first but then the whole line is evaluated but using the previous value of i.
So, to use another example that would make this more clear:
int i = 2;
System.out.println(i += i++); // Output: 4
System.out.println(i); // Output: 4
And another example:
int i = 2;
System.out.println(i = i + i++ + i--); // Output: 7
System.out.println(i); // Output: 7
The second line is assigning i. The first i is 2, the next i is also 2, but now the third i is 3 because i++ has changed the value of i. As the case from before, i-- will not have any affect on i because it will get rewritten with i = 2 + 2 + 3.
int i = 1;
System.out.println(i = i++ + i); // Output: 3
System.out.println(i); // Output: 3

1 + 1 == 2.
Therefore:
i + i == 2
and
i += i == 2
and then
i += i++ == 2
Pretty straight forward.

Related

Code after if block inside a for loop doesn't work

I'm new to java. This is a question about if block in a for loop. This code is from a algorithm practice.
The code is to take an int array but treat it as an integer and add one to this integer, and convert the new integer back to array format. if I didn't describe it clearly, please refer to the original here.
public static int[] plusOne(int[] digits) {
int size = digits.length;
for(int i=size-1; i>=0; i--) {
if(digits[i] < 9) {
System.out.println("tag1 digits.i = " + digits[i]);
digits[i]++;
System.out.println("tag2 digits.i = " + digits[i]);
return digits; // <-- return
}
System.out.println("tag3 digits.i= " + digits[i]);
digits[i] = 0; //?
System.out.println("tag4 digits.i= " + digits[i]);
}
int[] intOut = new int [size+1];
intOut[0] = 1;
return intOut;
}
In the codes above, I added some println() to show how digit[i] changes.
When the input is {1,2,3}, why the line of digits[i] = 0 doesnt work? Reading the code I thought all int in int[] digits will be set to 0.
If it return in the if block, does it mean stop the current iteration and ignore the rest code in the for loop after the if block?
update I failed to describe it clearly.My question was not on what and how to accomplish with the code, but about given the input i mentioned, why the code after if statement doesn't work. And now i learnt that the return statement at the last line of the if block means to do it(stop current iteration). Sorry for this silly question..!
Your code add one to the number passed as digit array.
So when you add 1 to 123, you get 124. The code starts with the last digit, looks whether it is less than 9, then add 1 only to the last digit.
this happens in the if-block. The return ends the function
The code which sets a digit to 0 will only reached when there is some overflow. This overflow can only happen when you pass a number where the last digit is 9.
To reach this case you must pass something like 129 (or {1,2,9}). Then the last digit become 0 and the second last digit is checked. In this case added by one, return 130
To reach the code behind the loop, you have to pass a list where all digits are set to 9. For example 99 (or {9,9}).
In this case, the last digit will set to 0, the first digit will set to 0, then a new list will be generates with one more digit. Initially all digits are set to 0. Then the first digit will be set to 1. This results in 100.
return leaves the function/method
break leaves the surrounding loop (for,while)
So the answer to your question in bold is YES
For the below loop:
for(int i=size-1; i>=0; i--) {
if(digits[i] < 9) {
System.out.println("tag1 digits.i = " + digits[i]);
digits[i]++;
System.out.println("tag2 digits.i = " + digits[i]);
return digits;
}
System.out.println("tag3 digits.i= " + digits[i]);
digits[i] = 0; //?
System.out.println("tag4 digits.i= " + digits[i]);
}
The moment digit[i] < 9 it will go inside the if condition. But after that it will return the digit[] and will come out of the method.
Hence you will never see digit[i] < 9 i.e. 1 to 8 being set to 0.

Can someone help me understand these 2 pieces of code [Recursion]?

I'm having a hard time trying to understand what is going on in this code. Out of the 14 questions we had for homework, these were the only 2 that I got stuck on and just put down the answer without knowing how they got to the answer. Any help would be appreciated, thank you.
Here is #1:
public void printDollarSign(int k)
{
int j;
if (k>0)
{
for (j=1; j<= k; j++)
System.out.print("$");
System.out.println();
printDollarSign(k-1);
}
}
What will be the output if the call is: printDollarSign(5); ?
Answer is:
$$$$$
$$$$
$$$
$$
$
Here is #2:
public void bbb(String s, int p)
{
if (p>= 0)
{
bbb(s,p-1);
System.out.print(s.charAt(p));
}
}
What will the output be if the call is: bbb("January" , 4); ?
Answer is:
Janua
Explanation for printDollarSign:
Here you have created a recursive function.
Every recursive function has a base condition.In your case its if (k>0).
Every recursive call decrements the value of k by 1.Hence for each recursive call ,the number of times your for loop runs is reduced by 1.
For the First call:
Suppose k = 5 ;
Function call printDollarSign(5);
Check if(k > 0 ) i.e 5 > 0 ;
For loop runs for 5 times and prints 5 "$" signs;
A println prints a line break;
Recursive call printDollarSign(4);
printDollarSign(k) first prints k number of $'s, then prints a newline and then calls printDollarSign(k-1) first to print k-1 number of $'s, then to print a newline and then to call printDollarSign(k-1-1)... this continues until k=0. When k=0, printDollarSign(0) prints nothing.
Add code comments for explanation:
1#
public void printDollarSign(int k)
{
// temporary variable j, it will be always initialized to 1 inside the for loop.
int j;
// only executed to be true if k is more than 0, that means if K is initially 5
// then it only works for 5,4,3,2,1 and not for 0.
if (k>0)
{
// always starts with 1 and goes to the value of k, that means if K is currently 5
// then it will print 5 dollars, if 4 then 4 dollars and so on
for (j=1; j<= k; j++)
System.out.print("$");
// a new line will be added once dollars are printed.
System.out.println();
// this will again call the same function and decrements the value of k, so next time
// k will have the value one less then the previous one, if this has printed 5 dollars
// in last iteration next time it will print 4 dollars and so on
printDollarSign(k-1);
}
}
2#
public void bbb(String s, int p)
{
// only print a character if p has a value grater than 0. in you case , p has a value 4 that
// mean only 4 characters will be printed at max
if (p>= 0)
{
// recuresively call same method by decrementing p, so it will be
// [bbb(s,3) prints 'a']-> [bbb(s,3) prints 'u']-> bbb(s,2) [prints 'n']-> [bbb(s, 1) prints 'a']> [bbb(s, 0) prints 'J']
// last character will be printed first
bbb(s,p-1);
// prints the character at p location
System.out.print(s.charAt(p));
}
}
Explanation for bbb:
It's an application of recursion to extract a substring from the given string.
Base condition if (p>= 0).
You should be aware about the fact that for each and every recursion call the value of "P" is stored in the stack.
As you know stack is a Last In First Out(LIFO) data structure , the last value inserted into the stack will be popped out first.
Execution:
bbb("January" , 4); --> Stack contains : [4]
bbb("January" , 3); --> Stack contains : [3 4]
bbb("January" , 2); --> Stack contains : [2 3 4]
bbb("January" , 1); --> Stack contains : [1 2 3 4]
bbb("January" , 0); --> Stack contains : [0 1 2 3 4]
Now pop out each element and print the char at that position
After 0 -> J
After 1 -> Ja
After 2 -> Jan
After 3 -> Janu
After 4 -> Janua
if you provide a string s as 'January', the way it stores is like this:
0th position = J,
1th position = a,
2th position = n,
3th position = u,
4th position = a,
5th position = r,
6th position = y,
Just like an array of characters.
When you provide p=4, you are setting the closing criteria for the condition check.
function bbb('January', 4){
if(4>=0){
bbb('January', 3); ....
function bbb('January', 3){
if(3>=0){
bbb('January', 2); ....
function bbb('January', 2){
if(2>=0){
bbb('January', 1); ....
function bbb('January', 1){
if(1>=0){
bbb('January', 0); ....
function bbb('January', 0){
if(0>=0){
bbb('January', -1); ....
function bbb('January', -1){
if(-1>=0){ Here condition check fails.. hence char at(-1) doec not print
return goes back to print of previous call and prints J as p=0, we have J
the p=1: a
p=2: n
p=3: u
p=4: a
and function finishes...
Kindly let me know if the explanation was helpful
Your first one, is creating a function with a specific parameter of an int, in this case "k".
It is then setting an int called j via "int k;"
It is then checking if k is greater than 0
After checking it is looping through k (where j = 1 and j < k) and printing out a "$" sign
It will produce "$$$$$".."$$$$".. etc.. till k < 0
Then write a new line, then call the function again minusing 1 from k
Code:
public void printDollarSign(int k){ //Define function
int j;//Define j as an int
if (k>0){//Check if k is greater than 0
for (j=1; j<= k; j++)//Loop through k where j = 1
System.out.print("$");//Print $ by the amount of k
System.out.println();//Print a new line
printDollarSign(k-1);//Re run the function
}
}
Your second question is creating a function with two parameters of string and int "s" and "p"
Its checking if p is greater than 0
Then calling the function inside itself minusing 1 from p (p-1)
Its then printing out a character from your string based on p
Code:
public void bbb(String s, int p){//Define Function
if (p>= 0){ //Check if p is greater than 0
bbb(s,p-1);//Rerun function
System.out.print(s.charAt(p));//Print character of string based on p
}
}

What is difference between while(++i < --j) & while(i++<j--)?

I try this below program which find midpoint between two no.
class FindMidPoint
{
public static void main(String args[])
{
int i, j;
i = 100;
j = 200;
// find midpoint between i and j
while(++i < --j) ;
System.out.println("Midpoint is " + i+" OR "+j);
}
}
Output:
Midpoint is 150 OR 150
But If I make changing in while condition that is
while(i++<j--)
Then output is:
Midpoint is 16 OR 14
I also refer the below Link then also I'm not understanding the difference between ++i & i++ in this program.
what is the difference between i++ & ++i in for loop (Java)?
Please explain me if anyone have idea about.
If you have i = 1 and j = 2. The first one compares 2 < 1 and the second one compares 1 < 2. (In the first one the decrementation/incrementation are done before the comparing, while in the second one they are done after the comparison)
The ++ before any variable present in an expression indicates that increment has to be made before the expression executes.
For example
int i=2;
int x = ++i + 2
Here since ++ is present before i, so first there will be an increment on i, and then the expression will be executed.
The steps involved is :
Step 1 :
++i : i=(i+1) = 3
Step2:
int x = ++i + 2 = 3+2=5
So after this expression executes : x=5 and i=3
But if you consider post increment:
For example:
int i=2;
int x = i++ + 2;
This means that increment will happen after the line is executed.
The steps are:
Step 1 :
int x = i++ + 2 = 2 + 2 =4; // i is still 2 here since the increment didn't happen by now
Step 2:
i++ : i=i+1 = 3;
So after the execution x=4 and i=3
++i
You could think something like increment the value and then use the incremented value in the expression
i++
Use the value in the expression before it gets incremented
Say we have the following code:
int i = 100;
int j = ++i + 50; // statement 1
Here j would have a value of 151, saying increment i first and then evaluate the expression, so 101+50.
Lets way we have
int j = i++ + 50; // statement 2
Here j would have a value of 150, saying evaluate the expression first, then increment the value i
However, i would be 101 after executing the second statement
Basic difference between pre and post should be applied here.
Pre increment operator ++i : equivalent to replacing i with i+1 and using result in the expression.
while(++i < --j);
//read as while( (i_new = i_old+1) < (j_new =j_old -1) );
//In next expression i will be value of i_new and j value will be j_new
Post increment operator i++ : equivalent to using the same value of i in the current expression. And in the next immediate expression use the increased value.
while(i++ < j--);
//read as while( (i_old < j_old );
//In next expression(even in next iteration of same above while) i will be value of i_old+1 and j value will be j_old-1
Its all about precedence, in java every operator has a precedence, pre-increment has very high precedence while post-increment come at last as compared to other operators.

need help to understand recursion

n = 10
10+9+8+7+6+5+4+3+2+1 = 55
here's a piece of code to add number starting from n, to every number before it.
public static int recursion(int index){
if (index == 0){
return 0;
}
else{
return recursion(index-1) + index;
}
}
sorry for stupid question, but here's what confuse me: when the index is not zero, it calls the recursion function again, with the index substracted by 1, so on until the index is zero. However, it's coded recursion(index-1) + index.
so why the index is not substracted by 1 and added by 10 (or any index number) each time the function is called? why is it not something like this: (10+ (9+10) + (8+10) + (7+10) +....) ?
Try to write this sum as
sum(10) = 1+2+3+4+5+6+7+8+9+10
This will let you see that
sum(10) = (1+2+3+4+5+6+7+8+9)+10 = sum(9)+10
and
sum(9) = (1+2+3+4+5+6+7+8)+9
and so on
In other words
sum(i) = sum(i-1) + i;
or to be more precise
{0 for i=0
sum(i) = {
{sum(i-1) + i for i>0
BTW each time method is called its variables are separate instances in each method call which means index in recursion(10) is separate variable than index in recursion(9).
Evaluate it by hand. Start with index = 10:
Index is not zero so we go into the else:
return recursion(10 - 1) + 10
return recursion(9) + 10
Now, recursion(9) evaluates to
return recursion(9 - 1) + 9
return recursion(8) + 9
So, substituting into the above:
return recursion(8) + 9 + 10
So, carrying on the process
return recursion(0) + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
And we know that recursion(0) returns 0 so the recursion stops at this point.
recursion(index-1) + index;
For this statement intiallty it will be
recursion(10-1) + index;
for evaluating that 10-1 will be done ie. 9
Then in order to find the ans of that statement recursion(9) has to be found so the function recursion is called again.
so expression becomes
recursion(9) + 10;
And recursion(9) wil be
recursion(9-1) + 9
This continues and finally it will be recursion(0) which returns 0.

Java - do loop help explaining needed

Why does the following code execute six times? Please help me to understand how this works, as I've tried to get it into my head without success.
I thought it would first execute the code once, then increase count to 1, execute it a second time, increase count to 2, execute it a third time, increase count to 3, execute it a fourth time, increase count to 4, execute it a fifth time, increase count to 5, and then stop. Which means it will have executed the loop five times (for the first time, then for when count is 1, 2, 3, 4).
int count = 0;
do {
System.out.println("Welcome to Java!");
} while (count++ < 5);
Have you tried running this code?
int count = 0;
do {
System.out.println("Welcome to Java! " + count);
} while (count++ < 5);
output:
Welcome to Java! 0
Welcome to Java! 1
Welcome to Java! 2
Welcome to Java! 3
Welcome to Java! 4
Welcome to Java! 5
This should help you understand what is happening. Has others have said your confusion is most likely in how the post increment operator works.
To help you understand pre and post increment operators lets run another code sample
int a = 0;
int b = 0;
System.out.println("pre increment "+ ++a);
System.out.println("post increment "+ b++);
output:
pre increment 1
post increment 0
Summarizing: with post increment the expression is evaluated before the variable is incremented, with pre increment the expression is evaluated after the variable is incremented.
Its postfix operator so first evalution of whole expression then increment
Control will flow like this
0
Welcome to Java!
//condition check : 0 then 1
Welcome to Java!
//condition check : 1 then 2
Welcome to Java!
//condition check : 2 then 3
Welcome to Java!
//condition check : 3 then 4
Welcome to Java!
//condition check : 4 then 5
Welcome to Java!
//condition check : 5 then 6
That's because you're using post-increment. The while condition is first evaluated (with the count value from BEFORE the increment) and then count is incremented.
Try ++count (which first increments and then returns value).
edit:
Note that although using it in
for(int i = 0; i < n; i++) {}
is ok (it will usually get optimized, etc.),
for(int i = 0; i < n; ++i) {}
is a little bit better from the semantic point of view IMO.
It gets even more complicated in languages with operator overloading, where i++ can have different sideffects than ++i.
count++; // <-- would execute the above code 6 times
is post increment and
++count; // <-- would execute the above code 5 times
is pre increment
Consider:
while (count++ < 5) System.out.println(count); // prints 1 2 3 4 5
while (++count < 5) System.out.println(count); // prints 1 2 3 4
So your do...while executes first without a comparison (because of the do) then runs the comparison.
If it's pre-increment it could be re written like this:
int count = 0;
do {
// print
count = count + 1;
} while (count < 5)
If it's post-increment it could be re written like this:
int count = 0;
while (count < 5) {
// print statement
count = count + 1;
}

Categories