Pre and Postfix Increment - java

a = 1;
int a2 = a++;
System.out.println("----------Test 3 ----------");
System.out.println("The value of a is " + a);
System.out.println("The value of a2 is " + a2);
System.out.println("The value of a2 is " + a2);
The result is :
----------Test 3 ----------
The value of a is 3
The value of a2 is 2
The value of a2 is 2
I don't understand why the value of a2 does not increase after the second output. Even a is increased using postfix increment and assigned to a2. Please explain it to me.

I don't understand why the value of a2 does not increase after the
second output even a is increased using postfix increment and assigned
to a2.
Let us go step by step:
a = 1
set the variable a to 1; Now:
int a2 = a++;
will be equivalent to:
int a2 = a;
a++;
first assigned and only then increment, hence the output:
The value of a is 2
The value of a2 is 1
The value of a2 is 1
and the name postfix increment.
For the behavior that you want use ++a instead, namely:
int a = 1;
int a2 = ++a;
System.out.println("The value of a is " + a);
System.out.println("The value of a2 is " + a2);
System.out.println("The value of a2 is " + a2);
Output:
The value of a is 2
The value of a2 is 2
The value of a2 is 2
In this case :
int a2 = ++a; is equivalent to :
a++;
int a2 = a;

The prefix and postfix increment only matter within the statement you are executing. Try adding prefix and postfix increments in the print statement.

that is how the post increment operator is designed to work...
doing
int a2 = a++;
is equivalent to doing
int a2 = a;
a = a + 1;
so your code is producing this output:
----------Test 3 ----------
The value of a is 2
The value of a2 is 1
The value of a2 is 1

Related

Increment and Decrement Operators output [duplicate]

Can you explain to me the output of this Java code?
int a=5,i;
i=++a + ++a + a++;
i=a++ + ++a + ++a;
a=++a + ++a + a++;
System.out.println(a);
System.out.println(i);
The output is 20 in both cases
++a increments and then uses the variable.
a++ uses and then increments the variable.
If you have
a = 1;
and you do
System.out.println(a++); //You will see 1
//Now a is 2
System.out.println(++a); //You will see 3
codaddict explains your particular snippet.
Does this help?
a = 5;
i=++a + ++a + a++; =>
i=6 + 7 + 7; (a=8)
a = 5;
i=a++ + ++a + ++a; =>
i=5 + 7 + 8; (a=8)
The main point is that ++a increments the value and immediately returns it.
a++ also increments the value (in the background) but returns unchanged value of the variable - what looks like it is executed later.
In both cases it first calculates value, but in post-increment it holds old value and after calculating returns it
++a
a = a + 1;
return a;
a++
temp = a;
a = a + 1;
return temp;
i = ++a + ++a + a++;
is
i = 6 + 7 + 7
Working: increment a to 6 (current value 6) + increment a to 7 (current value 7). Sum is 13 now add it to current value of a (=7) and then increment a to 8. Sum is 20 and value of a after the assignment completes is 8.
i = a++ + ++a + ++a;
is
i = 5 + 7 + 8
Working: At the start value of a is 5. Use it in the addition and then increment it to 6 (current value 6). Increment a from current value 6 to 7 to get other operand of +. Sum is 12 and current value of a is 7. Next increment a from 7 to 8 (current value = 8) and add it to previous sum 12 to get 20.
++a increments a before it is evaluated.
a++ evaluates a and then increments it.
Related to your expression given:
i = ((++a) + (++a) + (a++)) == ((6) + (7) + (7)); // a is 8 at the end
i = ((a++) + (++a) + (++a)) == ((5) + (7) + (8)); // a is 8 at the end
The parenteses I used above are implicitly used by Java. If you look at the terms this way you can easily see, that they are both the same as they are commutative.
In the above example
int a = 5,i;
i=++a + ++a + a++; //Ans: i = 6 + 7 + 7 = 20 then a = 8
i=a++ + ++a + ++a; //Ans: i = 8 + 10 + 11 = 29 then a = 11
a=++a + ++a + a++; //Ans: a = 12 + 13 + 13 = 38
System.out.println(a); //Ans: a = 38
System.out.println(i); //Ans: i = 29
I believe however if you combine all of your statements and run it in Java 8.1 you will get a different answer, at least that's what my experience says.
The code will work like this:
int a=5,i;
i=++a + ++a + a++; /*a = 5;
i=++a + ++a + a++; =>
i=6 + 7 + 7; (a=8); i=20;*/
i=a++ + ++a + ++a; /*a = 5;
i=a++ + ++a + ++a; =>
i=8 + 10 + 11; (a=11); i=29;*/
a=++a + ++a + a++; /*a=5;
a=++a + ++a + a++; =>
a=12 + 13 + 13; a=38;*/
System.out.println(a); //output: 38
System.out.println(i); //output: 29
++a is prefix increment operator:
the result is calculated and stored first,
then the variable is used.
a++ is postfix increment operator:
the variable is used first,
then the result is calculated and stored.
Once you remember the rules, EZ for ya to calculate everything!
Presuming that you meant
int a=5; int i;
i=++a + ++a + a++;
System.out.println(i);
a=5;
i=a++ + ++a + ++a;
System.out.println(i);
a=5;
a=++a + ++a + a++;
System.out.println(a);
This evaluates to:
i = (6, a is now 6) + (7, a is now 7) + (7, a is now 8)
so i is 6 + 7 + 7 = 20 and so 20 is printed.
i = (5, a is now 6) + (7, a is now 7) + (8, a is now 8)
so i is 5 + 7 + 8 = 20 and so 20 is printed again.
a = (6, a is now 6) + (7, a is now 7) + (7, a is now 8)
and after all of the right hand side is evaluated (including setting a to 8) THEN a is set to 6 + 7 + 7 = 20 and so 20 is printed a final time.
when a is 5, then a++ gives a 5 to the expression and increments a afterwards, while ++a increments a before passing the number to the expression (which gives a 6 to the expression in this case).
So you calculate
i = 6 + 7 + 7
i = 5 + 7 + 8
Pre-increment means that the variable is incremented BEFORE it's evaluated in the expression. Post-increment means that the variable is incremented AFTER it has been evaluated for use in the expression.
Therefore, look carefully and you'll see that all three assignments are arithmetically equivalent.
pre-increment and post increment are equivalent if not in an expression
int j =0;
int r=0
for(int v = 0; v<10; ++v) {
++r;
j++;
System.out.println(j+" "+r);
}
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
I believe you are executing all these statements differently
executing together will result => 38 ,29
int a=5,i;
i=++a + ++a + a++;
//this means i= 6+7+7=20 and when this result is stored in i,
//then last *a* will be incremented <br>
i=a++ + ++a + ++a;
//this means i= 5+7+8=20 (this could be complicated,
//but its working like this),<br>
a=++a + ++a + a++;
//as a is 6+7+7=20 (this is incremented like this)
a=5; i=++a + ++a + a++;
is
i = 7 + 6 + 7
Working: pre/post increment has "right to left" Associativity , and pre has precedence over post , so first of all pre increment will be solve as (++a + ++a) => 7 + 6 . then a=7 is provided to post increment => 7 + 6 + 7 =20 and a =8.
a=5; i=a++ + ++a + ++a;
is
i=7 + 7 + 6
Working: pre/post increment has "right to left" Associativity , and pre has precedence over post , so first of all pre increment will be solve as (++a + ++a) => 7 + 6.then a=7 is provided to post increment => 7 + 7 + 6 =20 and a =8.

Why post increment opertor failed to increment 'a' in this code?

package com;
public class Test {
public static void main(String[] args)
{
int a= 11, b = 10;
a = a++ + ++b; //why? output is "22 11" and not "23 11"
System.out.println(a+" "+b);
}
}
Here's how the expression gets evaluated (roughly, I didn't check the JLS for evaluation order but I think it's from left to right):
a = a++ + ++b; // a is 11, b is 10
a = 11 + ++b; // a is 12 but its previous value 11 was returned by a++, b is 10
a = 11 + 11; // a is 12, b is 11 and its updated value was returned by ++b
a = 22; // a is 12, b is 11 and its updated value was returned by ++b
Therefore, it's the expected result, you just have to apply the definition of those operators.
a++ means that "a" has old value in place where you write it and change it after. ++a means that "a" at fist change value and than will be calculate.
So:
a = 5;
b = 5;
So:
a++ + ++b = (5 (and a + 1 later) + (at first b + 1) 6.
I hope you understand me) My English is in the same level with your Java=)

Get the consecutive numbers whose sum matches with given number

I was going through a simple program that takes a number and finds the number of occurrences of consecutive numbers that matches with given number.
For example:
if input is 15, then the consecutive numbers that sum upto 15 are:
1,2,3,4,5
4,5,6
7,8
So the answer is 3 as we have 3 possibilities here.
When I was looking for a solution I found out below answer:
static long process(long input) {
long count = 0;
for (long j = 2; j < input/ 2; j++) {
long temp = (j * (j + 1)) / 2;
if (temp > input) {
break;
}
if ((input- temp) % j == 0) {
count++;
}
}
return count;
}
I am not able to understand how this solves the requirement because this program is using some formula which I am not able to understand properly, below are my doubts:
The for loop starts from 2, what is the reason for this?
long temp = (j * (j + 1)) / 2; What does this logic indicates? How is this helpful to solving the problem?
if ((num - temp) % j == 0) Also what does this indicate?
Please help me in understanding this solution.
I will try to explain this as simple as possible.
If input is 15, then the consecutive numbers that sum upto 15 are:
{1,2,3,4,5} -> 5 numbers
{4,5,6} -> 3 numbers
{7,8} -> 2 numbers
At worst case, this must be less than the Sum of 1st n natural numbers = (n*(n+1) /2.
So for a number 15, there can never be a combination of 6 consecutive numbers summing up to 15 as the sum of 1st 6 numbers =21 which is greater than 15.
Calculate temp: This is (j*(j+1))/2.
Take an example. Let input = 15. Let j =2.
temp = 2*3/2 = 3; #Meaning 1+2 =3
For a 2-number pair, let the 2 terms be 'a+1' and 'a+2'.(Because we know that the numbers are consecutive.)
Now, according to the question, the sum must add up to the number.
This means 2a+3 =15;
And if (15-3) is divisible by 2, 'a' can be found. a=6 -> a+1=7 and a+2=8
Similarly, let a+1 ,a+2 and a+3
a + 1 + a + 2 + a + 3 = 15
3a + 6 = 15
(15-6) must be divisible by 3.
Finally, for 5 consecutive numbers a+1,a+2,a+3,a+4,a+5 , we have
5a + 15 = 15;
(15-15) must be divisible by 5.
So, the count will be changed for j =2,3 and 5 when the input is 15
If the loop were to start from 1, then we would be counting 1 number set too -> {15} which is not needed
To summarize:
1) The for loop starts from 2, what is the reason for this?
We are not worried about 1-number set here.
2) long temp = (j * (j + 1)) / 2; What does this logic indicates? How is this helpful to solving the problem?
This is because of the sum of 1st n natural numbers property as I have
explained the above by taking a+1 and a+2 as 2 consecutive
numbers.
3) if ((num - temp) % j == 0) Also what does this indicate?
This indicates the logic that the input subtracted from the sum of 1st
j natural numbers must be divisible by j.
We need to find all as and ns, that for given b the following is true:
a + (a + 1) + (a + 2) + ... (a + (n - 1)) = b
The left side is an arithmetic progression and can be written as:
(a + (n - 1) / 2) * n = b (*)
To find the limit value of n, we know, that a > 0, so:
(1 + (n - 1) / 2) * n = n(n + 1) / 2 <= b
n(n + 1) <= 2b
n^2 + n + 1/4 <= 2b + 1/4
(n + 1/2)^2 <= 2b + 1/4
n <= sqrt(2b + 1/4) - 1/2
Now we can rewrite (*) to get formula for a:
a = b / n - (n - 1) / 2
Example for b = 15 and n = 3:
15 / 3 - (3 - 1) / 2 = 4 => 4 + 5 + 6 = 15
And now the code:
double b = 15;
for (double n = 2; n <= Math.ceil(Math.sqrt(2 * b + .25) - .5); n++) {
double candidate = b / n - (n - 1) / 2;
if (candidate == (int) candidate) {
System.out.println("" + candidate + IntStream.range(1, (int) n).mapToObj(i -> " + " + (candidate + i)).reduce((s1, s2) -> s1 + s2).get() + " = " + b);
}
}
The result is:
7.0 + 8.0 = 15.0
4.0 + 5.0 + 6.0 = 15.0
1.0 + 2.0 + 3.0 + 4.0 + 5.0 = 15.0
We are looking for consecutive numbers that sum up to the given number.
It's quite obvious that there could be at most one series with a given length, so basically we are looking for those values witch could be the length of such a series.
variable 'j' is the tested length. It starts from 2 because the series must be at least 2 long.
variable 'temp' is the sum of a arithmetic progression from 1 to 'j'.
If there is a proper series then let X the first element. In this case 'input' = j*(X-1) + temp.
(So if temp> input then we finished)
At the last line it checks if there is an integer solution of the equation. If there is, then increase the counter, because there is a series with j element which is a solution.
Actually the solution is wrong, because it won't find solution if input = 3. (It will terminate immediately.) the cycle should be:
for(long j=2;;j++)
The other condition terminates the cycle faster anyway.
NB: loop is starting from 2 because=> (1*(1+1))/2 == 1, which doesn't make sense, i.e, it doesn't effect on the progress;
let, k = 21;
so loop will iterate upto (k/2) => 10 times;
temp = (j*(j+1))/2 => which is, 3 when j =2, 6 when j = 3, and so on (it calculates sum of N natural numbers)
temp > k => will break the loop because, we don't need to iterate the loop when we got 'sum' which is more than 'K'
((k-temp)%j) == 0 => it is basically true when the input subtracted from the sum of first j natural numbers are be divisible by j, if so then increment the count to get total numbers of such equation!
public static long process(long input) {
long count = 0, rest_of_sum;
for (long length = 2; length < input / 2; length++) {
long partial_sum = (length * (length + 1)) / 2;
if (partial_sum > input) {
break;
}
rest_of_sum = input - partial_sum
if (rest_of_sum % length == 0)
count++;
}
return count;
}
input - given input number here it is 15
length - consecutive numbers length this is at-least 2 at max input/2
partial_sum = sum of numbers from 1 to length (which is a*(a+1)/2 for 1 to a numbers) assume this is a partial sequence
rest_of_sum = indicates the balance left in input
if rest of sum is multiple of length meaning is that we can add (rest_of_sum/length) to our partial sequence
lets call (rest_of_sum/length) as k
this only means we can build a sequence here that sums up to our input number
starting with (k+1) , (k+2), ... (k+length)
this can validated now
(k+1) + (k+2) + ... (k+length)
we can reduce this as k+k+k+.. length times + (1+2+3..length)
can be reduced as => k* length + partial_sum
can be reduced as => input (since we verified this now)
So idea here is to increment count every-time we find a length which satisfies this case here
If you put this tweak in it may fix code. I have not extensively tested it. It's an odd one but it puts the code through an extra iteration to fix the early miscalculations. Even 1/20000 would work! Had this been done with floats that got rounded down and 1 added to them I think that would have worked too:
for (long j = 2; j < input+ (1/2); j++) {
In essence you need to only know one formula:
The sum of the numbers m..n (or m to n) (and where n>m in code)
This is ((n-m+1)*(n+m))/2
As I have commented already the code in the original question was bugged.
See here.
Trying feeding it 3. That has 1 occurrence of the consecutive numbers 1,2. It yields 0.
Or 5. That has 2,3 - should yield 1 too - gives 0.
Or 6. This has 1,2,3 - should yield 1 too - gives 0.
In your original code, temp or (j * (j + 1)) / 2 represented the sum of the numbers 1 to j.
1 2 3 4 5
5 4 3 2 1
=======
6 6 6 6 6 => (5 x 6) /2 => 30/2 => 15
As I have shown in the code below - use System.out.println(); to spew out debugging info.
If you want to perfect it make sure m and n's upper limits are half i, and i+1 respectively, rounding down if odd. e.g: (i=15 -> m=7 & n=8)
The code:
class Playground {
private static class CountRes {
String ranges;
long count;
CountRes(String ranges, long count) {
this.ranges = ranges;
this.count = count;
}
String getRanges() {
return this.ranges;
}
long getCount() {
return this.count;
}
}
static long sumMtoN(long m, long n) {
return ((n-m+1)* (n+m))/2;
}
static Playground.CountRes countConsecutiveSums(long i, boolean d) {
long count = 0;
StringBuilder res = new StringBuilder("[");
for (long m = 1; m< 10; m++) {
for (long n = m+1; n<=10; n++) {
long r = Playground.sumMtoN(m,n);
if (d) {
System.out.println(String.format("%d..%d %d",m,n, r));
}
if (i == r) {
count++;
StringBuilder s = new StringBuilder(String.format("[%d..%d], ",m,n));
res.append(s);
}
}
}
if (res.length() > 2) {
res = new StringBuilder(res.substring(0,res.length()-2));
}
res.append("]");
return new CountRes(res.toString(), count);
}
public static void main(String[ ] args) {
Playground.CountRes o = countConsecutiveSums(3, true);
for (long i=3; i<=15; i++) {
o = Playground.countConsecutiveSums(i,false);
System.out.println(String.format("i: %d Count: %d Instances: %s", i, o.getCount(), o.getRanges()));
}
}
}
You can try running it here
The output:
1..2 3
1..3 6
1..4 10
1..5 15
1..6 21
1..7 28
1..8 36
1..9 45
1..10 55
2..3 5
2..4 9
2..5 14
2..6 20
2..7 27
2..8 35
2..9 44
2..10 54
3..4 7
3..5 12
3..6 18
3..7 25
3..8 33
3..9 42
3..10 52
4..5 9
4..6 15
4..7 22
4..8 30
4..9 39
4..10 49
5..6 11
5..7 18
5..8 26
5..9 35
5..10 45
6..7 13
6..8 21
6..9 30
6..10 40
7..8 15
7..9 24
7..10 34
8..9 17
8..10 27
9..10 19
i: 3 Count: 1 Instances: [[1..2]]
i: 4 Count: 0 Instances: []
i: 5 Count: 1 Instances: [[2..3]]
i: 6 Count: 1 Instances: [[1..3]]
i: 7 Count: 1 Instances: [[3..4]]
i: 8 Count: 0 Instances: []
i: 9 Count: 2 Instances: [[2..4], [4..5]]
i: 10 Count: 1 Instances: [[1..4]]
i: 11 Count: 1 Instances: [[5..6]]
i: 12 Count: 1 Instances: [[3..5]]
i: 13 Count: 1 Instances: [[6..7]]
i: 14 Count: 1 Instances: [[2..5]]
i: 15 Count: 3 Instances: [[1..5], [4..6], [7..8]]

Post Increment with substitution

I have a question here already of my own but I want to extend it Post increment with example
char a = 'D';
int b = 5;
System.out.println(a++/b+--a*b++);
As one of the answers for the question is:
(68 / 5) + (68 * 5) and b++ doesnt have the effect on this .
My doubt is if b++ doesnt have effect then why a++ is having the effect?
Ideally it should have been
Step 1: (68/b+--a*b++);
Now a = 69;
Step 2: (68/b+--a*5)
Now a = 69;
b =6;
Step 3: (68/b+68*5)
Step 4: (68/6+68*5)
Answer which 351 but the answer epected is 353
Don't confused evaluation order with precedence.
Evaluation order states that operands are always executed left to right.
Precedence states that * and / operators are applied before + and -, unless overridden by parenthesis.
So, you're right that a++/b+--a*b++ means (a++ / b) + (--a * b++). That's precedence.
Since numeric operators promote values to int (in this case), you're also right that char a = 'D' is equivalent to int a = 68.
So:
(a++ / b) + (--a * b++) a = 68 b = 5
(68 / b) + (--a * b++) a = 69 b = 5
(68 / 5) + (--a * b++) a = 69 b = 5
(68 / 5) + (68 * b++) a = 68 b = 5
(68 / 5) + (68 * 5 ) a = 68 b = 6
13 + 340 a = 68 b = 6
353 a = 68 b = 6
As you can see, b++ does have an effect: On the value of b after executing the expression.
Step 4: (68/6+68*5) its your wrong!
b is 5 in all positions in the calculation instead of it's value 6.
so we have:
Step 4: (68/5+68*5) = (13+340)=353

Increment Decrement operator use [duplicate]

This question already has answers here:
How do the post increment (i++) and pre increment (++i) operators work in Java?
(14 answers)
Closed 5 years ago.
In the below programs , post increment operator is used just after completion of expression evaluation. Now for the first program shouldn't the answer be 40 n then value of a be incremented to 41.N likewise for program 2 answer should be 41 instead of 42?
class IncrementDemo{
public static void main(String [] args){
int a=20;
a= a++ + a++;
System.out.println(a); //Answer given is 41
}
class IncrementDemo{
public static void main(String [] args){
int a=20;
a= a++ + ++a;
System.out.println(a);
}
Answer given is 42 for second program.
You can understand the behaviour if you analyze how the statement is executed and the state of a in the meanwhile.
a = 20
a++ is executed, 20 is the result of the evaluation, a = 21
the second a++ is executed, 21 is the result, a = 22
the two results are added, 20 + 21 = 41, a = 41
on the other side, in the second case:
a = 20
a++ is executed, 20 is the result of the evaluation, a = 21
++a is executed, a = 22, 22 is the result
the two results are added, 20 + 22 = 42, a = 42
This is because the two increment operators are evaluated sequentially, so the second sees the effect of the first one.
The difference between those two is, that ++a will increment the value of a and return the incremented value. On the other hand a++ will increment the value, but return the original value that a had before being incremented.
The results are correct.
First case
int a=20;
a= a++ + a++;
This results in the following evaluation steps:
a = a++ + a++ (with a=20)
a = 20 + a++ (with a=21)
a = 20 + 21 (with a=22)
Second case
int a=20;
a= a++ + ++a;
This results in the following evaluation steps:
a = a++ + ++a (with a=20)
a = 20 + ++a (with a=21)
a = 20 + 22 (with a=22)
When operator used in prefix mode, it increments the operand and
evaluates to the incremented value of that operand. When used in
postfix mode, it increments its operand, but evaluates to the value of
that operand before it was incremented.
a= a++ + a++;
so first a++ will yield 20, now a value become 21
second a++ will yield 21, so final operation return 20+21 = 41
similar for second program
int a=20;
a= a++ + ++a;
First a++ will yield 20, now a value become 21
second ++a will yield value 22
combining both will return result 20+22 = 42
a = a++ + a++
For the first a++, the value of a being used for the calculation is its actual value: 20, and after that it is incremented to 21.
So, for the second a++, the value used for the calculation, is also the actual value of a, but this time it is 21 because it has been incremented in the first a++.
So you have 20 + 21, hence 41.
a = a++ + ++a
Same thing for a++, the actual value of a, 20 is used for the calculation, and then it is incremented to 21.
Then ++a, the value is incremented before it is used, so it becomes 22, and then it is used for the calculation.
So you have 20 + 22, hence 42.

Categories