Increment in for loop give different answers [duplicate] - java

This question already has answers here:
How do the post increment (i++) and pre increment (++i) operators work in Java?
(14 answers)
Closed 4 years ago.
class Test {
public static void main(String[] args) {
for (int i= 1; i < 2; i++) {
System.out.println(i);
System.out.println(++i);
int a = 1;
System.out.println(a++);
System.out.println(++a);
}
}
}
The output here is 1,2 and 1,3. We are doing post-increment and pre-increment in both the cases why I am getting different results?

Because post increment happens at the end of the iteration.
Hence the below code :
for (int i= 1; i < 2; i++) {
System.out.println(i);
System.out.println(++i);
Will work something like this:
int i = 1;
System.out.println(i); // i is still 1
System.out.println(++i); // pre increment making i to 2 and then print
i++;
if(i<2)
// iterate again
However, in second case:
int a = 1;
System.out.println(a++); // post increment first print 1 and then change a to 2
System.out.println(++a); // pre increment a now changed to 3

System.out.println(i); // 1 (initial value)
System.out.println(++i); // 2 (pre increment returns the value after increment)
int a = 1;
System.out.println(a++); // 1 (initial value prior to increment, since post increment
// returns the value prior to increment)
System.out.println(++a); // 3 (pre increment returns the value after increment)
The i++ in the loop's definition only takes place at the end of each iteration. You never print the value of i after i++ is executed, since the loop terminates after the first iteration.
BTW, if i++ was executed prior to System.out.println(i);, you'd still get a different output (compared to the last two println statements) - 2 followed by 3.

The general structure of a for loop (more precisely: this type of basic for statement) is:
for ([ForInit]; [Expression]; [ForUpdate]) Statement
The equivalent while loop is:
[ForInit];
while ([Expression]) {
Statement;
[ForUpdate];
}
In other words, the update is executed after the loop body.
So your code is equivalent to:
// ForInit
int i = 1;
while (/* Expression */ i < 2) {
// Statement
System.out.println(i);
System.out.println(++i);
int a = 1;
System.out.println(a++);
System.out.println(++a);
// ForUpdate
i++;
}
Hopefully it is then easy to see why there is a difference in the output.

In the first case, the post-increment is not called. If you understand how a for loop works, you will know that the increment section is not executed the very first time. The initialization section, here int i = 1, and the condition checking - i < 2 is validated. The increment section is invoked only after each iteration.
In the second case, the post-increment is performed and hence the difference in values. You should focus more on the basics of looping.

System.out.println(i);
i isn't postincremented here. The answers would be the same if it were:
System.out.println(i++);
System.out.println(++i);
int a = 1;
System.out.println(a++);
System.out.println(++a);
for (int i= 1; i < 2; **i++)**
doesn't do anything until a pass through loop is done.

Related

Java - For loop seems to execute past it's termination condition

I have debugged this code and it appears to run a for loop even though the termination condition is met.
This program takes two types of input:
Line 1 - How many data points there are following (N)
Lines 2 to N - The data points
The program should then print the smallest difference between all of the data points.
So, for instance, a sample input would be (on separate lines): 3 5 8 9
There are 3 data points (5 8 9), and the smallest difference is between 8 and 9, so the program should return 1.
I am trying to build the program in a way in which the data points are populated into an array at the same time as the comparisons are made. Obviously I could separate those concerns, but I am experimenting. Here it is:
package com.m3c.vks.test;
import java.util.*;
import java.io.*;
import java.math.*;
class Solution {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int N = in.nextInt(); //How many data points there will be
int strengthArray[] = new int[N]; //Initialise the array to be of length = N, the first input line
int tempStrengthDifference=99999; //junk difference set arbitrarily high - bad practice I know
int lowestStrengthDifference=99999;
for (int i = 0; i < N; i++) //Go through all elements of array
{
strengthArray[i] = in.nextInt(); //read a value for the ith element
System.out.println("i: " + i); //test
if (i > 0) //do not execute the next for loop if i = 0 as cannot evaluate sA[-1]
{
for (int j = i - 1; j < 1; j--) // **this is line 20** from wherever the array has populated up to, work backwards to compare the numbers which have been fed in thus far
{
System.out.println("j: " + j); //test
tempStrengthDifference = Math.abs(strengthArray[i] - strengthArray[j]); //finding the difference between two values
if (tempStrengthDifference < lowestStrengthDifference) //store the lowest found thus far in lowestSD
{
lowestStrengthDifference = tempStrengthDifference;
}
}
}
}
System.out.println(lowestStrengthDifference);
}
}
Everything is fine up until when i = 1 on line 20. At this point, j is set to i - 1 = 0 and the difference is found. However, when the for loop comes back around again, the termination condition of j < 1 is not met, and instead the loop continues to set j = -1, at which point it throws an out of bounds error as it clearly cannot evaluate strengthArray[-1]
Any ideas? Thanks
Have a look at your loop: for (int j = i - 1; j < 1; j--)
You start with j = 0 when i == 1 and thus j < 1 is ok.
The next iteration has j = -1 (0-1) and hence you get the problem.
Do you mean to use j >= 0 as your loop condition instead? Note that the second parameter is not a termination condition but a continuation condition, i.e. as long as that condition is met the loop will execute.
The reason behind your failure is the inner loop variable change.
When i=1, j=0 and after executing the loop once, J is decremented, and thus j becomes - 1. The condition j<1 is satisfied since you have written j--, change it to j++ and you should be fine.

understanding increment and decrement [duplicate]

From the program below or here, why does the last call to System.out.println(i) print the value 7?
class PrePostDemo {
public static void main(String[] args) {
int i = 3;
i++;
System.out.println(i); // "4"
++i;
System.out.println(i); // "5"
System.out.println(++i); // "6"
System.out.println(i++); // "6"
System.out.println(i); // "7"
}
}
i = 5;
System.out.println(++i); //6
This prints out "6" because it takes i, adds one to it, and returns the value: 5+1=6. This is prefixing, adding to the number before using it in the operation.
i = 6;
System.out.println(i++); //6 (i = 7, prints 6)
This prints out "6" because it takes i, stores a copy, adds 1 to the variable, and then returns the copy. So you get the value that i was, but also increment it at the same time. Therefore you print out the old value but it gets incremented. The beauty of a postfix increment.
Then when you print out i, it shows the real value of i because it had been incremented: 7.
Another way to illustrate it is:
++i will give the result of the new i, i++ will give the result of the original i and store the new i for the next action.
A way to think of it is, doing something else within the expression. When you are printing the current value of i, it will depend upon whether i has been changed within the expression or after the expression.
int i = 1;
result i = ++i * 2 // result = 4, i = 2
i is evaluated (changed) before the result is calculated. Printing i for this expression, shows the changed value of i used for this expression.
result i = i++ * 2 // result = 2, i = 2
i is evaluated after the result in calculated. So printing i from this expression gives the original value of i used in this expression, but i is still changed for any further uses. So printing the value for i immediately after the expression, will show the new incremented value of i. As the value of i has changed, whether it is printed or used.
result i = i++ * 2 // result = 2, i = 2
System.out.println(i); // 2
If you kept a consistent pattern and included print lines for all the values:
int i = 3;
System.out.println(i); // 3
System.out.println(i++); // 3
System.out.println(i); // "4"
System.out.println(++i); // 5
System.out.println(i); // "5"
System.out.println(++i); // "6"
System.out.println(i++); // "6"
System.out.println(i); // "7"
Think of ++i and i++ as similar to i = i+1. But it is not the same. The difference is when i gets the new increment.
In ++i , the increment happens immediately.
But if i++ is there, the increment will happen when the program goes to the next line.
Look at the code here.
int i = 0;
while(i < 10){
System.out.println(i);
i = increment(i);
}
private int increment(i){
return i++;
}
This will result in a nonending loop. Because i will be returned with the original value and after the semicolon, i will get incremented, but the returned value has not been. Therefore i will never actually returned as an incremented value.
Why wouldn't the variable have been updated?
Postfix: passes the current value of i to the function and then increments it.
Prefix: increments the current value and then passes it to the function.
The lines where you don't do anything with i make no difference.
Notice that this is also true for assignments:
i = 0;
test = ++i; // 1
test2 = i++; // 1
System.out.println(i++); // "6"
This sends println the value I had prior to this line of code (6), and then increments I (to 7).
An example of how the actual operators are implemented:
class Integer {
private int __i;
function Integer ++() { // Prefix operator i.e. ++x
__i += 1; // Increment
return this; // Return the object with the incremented value
}
function Integer ++(Integer x) { // Postfix operator, i.e., x++
__i+=1; // Increment
return x; // Return the original object
}
}
Maybe you can understand better Prefix/postfix with this example.
public class TestPrefixPostFix
{
public static void main (String[] args)
{
int x = 10;
System.out.println((x++ % 2 == 0) ? "yes " + x: " no " + x);
x = 10;
System.out.println((++x % 2 == 0) ? "yes " + x: " no " + x);
}
}
This may be easy to understand:
package package02;
public class C11PostfixAndPrefix {
public static void main(String[] args) {
// In this program, we will use the value of x for understanding prefix
// and the value of y for understaning postfix.
// Let's see how it works.
int x = 5;
int y = 5;
Line 13: System.out.println(++x); // 6 This is prefixing. 1 is added before x is used.
Line 14: System.out.println(y++); // 5 This is postfixing. y is used first and 1 is added.
System.out.println("---------- just for differentiating");
System.out.println(x); // 6 In prefixing, the value is same as before {See line 13}
System.out.println(y); // 6 In postfixing, the value increases by 1 {See line 14}
// Conclusion: In prefixing (++x), the value of x gets increased first and the used
// in an operation. While, in postfixing (y++), the value is used first and changed by
// adding the number.
}
}
It prints 7 for the last statement, because in the statement above, its value is 6 and it's incremented to 7 when the last statement gets printed.
This might help... it also took my to understand this puzzle.
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 5;
System.out.println(++x);
System.out.println(y++);
System.out.println("------");
System.out.println(x);
System.out.println(y);
}
}
Well, think of it in terms of temporary variables.
i = 3;
i ++; // Is equivalent to: temp = i++; and so, temp = 3 and then "i" will increment and become i = 4;
System.out.println(i); // Will print 4
Now,
i = 3;
System.out.println(i++);
is equivalent to
temp = i++; // 'temp' will assume a value of the current "i", after which "i" will increment and become i = 4
System.out.println(temp); // We're printing 'temp' and not "i"

When to use post increment and pre increment in Java [duplicate]

This question already has answers here:
How do the post increment (i++) and pre increment (++i) operators work in Java?
(14 answers)
Closed 7 years ago.
I understand that there are a number of questions on this topic on StackOverflow. But I am still slightly confused and unsure of when to use the operations. I am going through old tests in studying for my exam. One of the methods returns the number of classrooms that are handicapped accessible and are available. I wrote the counter method but am not sure if I am supposed to pre-increment or post increment the counter. I am confused as to how it works with return statement in methods. I still do not get what value the method will return below. The other questions do not show return values in methods and thus I am confused as to practically how it works. Here is the code:
public int howManyHandi()
{
int counter= 0;
for (int i = 0; i < _clsrms.length; i++){
if (_clsrms[i].handicappedSuitable() && _clsrms[i].isAvailable()){
++counter;
}
}
return counter;
}
PRE-increment is used when you want to use the incremented value of the variable in that expression., whereas POST-increment uses the original value before incrementing it.
Whenever your code encounters a PRE-increment, it increments the value of that variable in the memory, then load that value and continues reading the expression.
POST-increment does the opposite, it loads that value of that variable in the memory, then increments the value and continues reading the expression.
To make it more clear, consider this
int i = counter++;
is equivalent to
int i = counter;
counter = counter + 1;
WHEREAS
int i = ++counter;
is equivalent to
counter = counter + 1;
int i = counter;
EDIT: My StackOverflow comments arent working, so I'll just edit it here.
What I'm saying it, it only matters when you use that value in an expression.
sum = 0
counter = 0;
sum = (++counter)+(++counter)+(counter++)
evaluates as
sum = 0
counter = 0
//For first ++counter
counter = counter + 1
sum = counter
//For second ++counter
counter = counter + 1
sum = sum + counter
//For first counter++
sum = sum + counter
counter = counter + 1
In your example it doesn't matter, since you do nothing with the value returned by ++counter.
The only time it makes a difference is when you are using the value returned by the post/pre-increment operator.
For example, if you had a return counter++; or a return ++counter; statement, your method would return a different result based on which operator you used.

two loops in a function?

Is it possible to have two loops in a function?
public static void reduce(Rational fraction){
int divisorNum = 0;
int n = 2;
while(n < fraction.num){
if(fraction.num % n == 0){
divisorNum = n;
System.out.println("n: " + divisorNum);
n++;
}
}
int divisorDenom = 1;
int m = 2;
while(m<fraction.denom){
if(fraction.denom % m == 0){
divisorDenom = m;
System.out.println("m: " + divisorDenom);
m++;
}
}
}
I'm trying to get the greatest common denominator. I know this is the very long way about doing this problem but I just wanted to try having two loops. When I call this function, only the first loop gets printed and not the second. I originally had an if statement, but seeing that the second loop doesn't execute I figured that I fix this part first.
Here's my other part of the code:
public static void main(String[] args){
Rational fraction = new Rational();
fraction.num = 36;
fraction.denom = 20;
reduce(fraction);
}
Absolutely. There are no limitations
Watch your conditional test = is not quite ==
Based on your edit I suspect fraction.denom is initialized at 1 or 0
Hence you will never get in the second loop
You can have any number of loops in your function :-
1.You can have nested loops;
2.Two loops side by side.
SO,your piece of code is fine enough considering the value of n, until the conditions for loop execution are met :-
public static void ....
while(n<x){
do this
add to counter
}
while(m<x){
do this
add to counter
}
if(y==z){ // NOTE :- Here you have committed mistake, compare using ==, not by =(it will be always true else and your condition will always be met else)
print this
}
Yup. You even can have 3 if you try hard enough.
EDIT: The didactic version:
Loops, as the name suggest, are constructs that allow you to repeat blocks of code several times (post conditional loops -> until certain condition is met keep running, pre conditional loops -> if certain condition is met, keep running). This is often called "iteration". So in a typical for-loop:
for ( int i = 0; i < 10; ++i )
print(array[i]);
You can say you're "iterating" over the array 10 times.
This has nothing to do with functions. You can have several loops inside a function, or functions being called inside loops. As long as you define your "blocks" of code (with begining and ending braces) you do what you think its best.
Yes, there are no limitations when it comes to looping. You could do 1000 while loops if you wanted.
An example here could be doing something like making a square out of *...
Here's an example
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
System.out.print("*");
}
System.out.println();
}
It would look like:
****
****
****
****

Java: Prefix/postfix of increment/decrement operators

From the program below or here, why does the last call to System.out.println(i) print the value 7?
class PrePostDemo {
public static void main(String[] args) {
int i = 3;
i++;
System.out.println(i); // "4"
++i;
System.out.println(i); // "5"
System.out.println(++i); // "6"
System.out.println(i++); // "6"
System.out.println(i); // "7"
}
}
i = 5;
System.out.println(++i); //6
This prints out "6" because it takes i, adds one to it, and returns the value: 5+1=6. This is prefixing, adding to the number before using it in the operation.
i = 6;
System.out.println(i++); //6 (i = 7, prints 6)
This prints out "6" because it takes i, stores a copy, adds 1 to the variable, and then returns the copy. So you get the value that i was, but also increment it at the same time. Therefore you print out the old value but it gets incremented. The beauty of a postfix increment.
Then when you print out i, it shows the real value of i because it had been incremented: 7.
Another way to illustrate it is:
++i will give the result of the new i, i++ will give the result of the original i and store the new i for the next action.
A way to think of it is, doing something else within the expression. When you are printing the current value of i, it will depend upon whether i has been changed within the expression or after the expression.
int i = 1;
result i = ++i * 2 // result = 4, i = 2
i is evaluated (changed) before the result is calculated. Printing i for this expression, shows the changed value of i used for this expression.
result i = i++ * 2 // result = 2, i = 2
i is evaluated after the result in calculated. So printing i from this expression gives the original value of i used in this expression, but i is still changed for any further uses. So printing the value for i immediately after the expression, will show the new incremented value of i. As the value of i has changed, whether it is printed or used.
result i = i++ * 2 // result = 2, i = 2
System.out.println(i); // 2
If you kept a consistent pattern and included print lines for all the values:
int i = 3;
System.out.println(i); // 3
System.out.println(i++); // 3
System.out.println(i); // "4"
System.out.println(++i); // 5
System.out.println(i); // "5"
System.out.println(++i); // "6"
System.out.println(i++); // "6"
System.out.println(i); // "7"
Think of ++i and i++ as similar to i = i+1. But it is not the same. The difference is when i gets the new increment.
In ++i , the increment happens immediately.
But if i++ is there, the increment will happen when the program goes to the next line.
Look at the code here.
int i = 0;
while(i < 10){
System.out.println(i);
i = increment(i);
}
private int increment(i){
return i++;
}
This will result in a nonending loop. Because i will be returned with the original value and after the semicolon, i will get incremented, but the returned value has not been. Therefore i will never actually returned as an incremented value.
Why wouldn't the variable have been updated?
Postfix: passes the current value of i to the function and then increments it.
Prefix: increments the current value and then passes it to the function.
The lines where you don't do anything with i make no difference.
Notice that this is also true for assignments:
i = 0;
test = ++i; // 1
test2 = i++; // 1
System.out.println(i++); // "6"
This sends println the value I had prior to this line of code (6), and then increments I (to 7).
An example of how the actual operators are implemented:
class Integer {
private int __i;
function Integer ++() { // Prefix operator i.e. ++x
__i += 1; // Increment
return this; // Return the object with the incremented value
}
function Integer ++(Integer x) { // Postfix operator, i.e., x++
__i+=1; // Increment
return x; // Return the original object
}
}
Maybe you can understand better Prefix/postfix with this example.
public class TestPrefixPostFix
{
public static void main (String[] args)
{
int x = 10;
System.out.println((x++ % 2 == 0) ? "yes " + x: " no " + x);
x = 10;
System.out.println((++x % 2 == 0) ? "yes " + x: " no " + x);
}
}
This may be easy to understand:
package package02;
public class C11PostfixAndPrefix {
public static void main(String[] args) {
// In this program, we will use the value of x for understanding prefix
// and the value of y for understaning postfix.
// Let's see how it works.
int x = 5;
int y = 5;
Line 13: System.out.println(++x); // 6 This is prefixing. 1 is added before x is used.
Line 14: System.out.println(y++); // 5 This is postfixing. y is used first and 1 is added.
System.out.println("---------- just for differentiating");
System.out.println(x); // 6 In prefixing, the value is same as before {See line 13}
System.out.println(y); // 6 In postfixing, the value increases by 1 {See line 14}
// Conclusion: In prefixing (++x), the value of x gets increased first and the used
// in an operation. While, in postfixing (y++), the value is used first and changed by
// adding the number.
}
}
It prints 7 for the last statement, because in the statement above, its value is 6 and it's incremented to 7 when the last statement gets printed.
This might help... it also took my to understand this puzzle.
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 5;
System.out.println(++x);
System.out.println(y++);
System.out.println("------");
System.out.println(x);
System.out.println(y);
}
}
Well, think of it in terms of temporary variables.
i = 3;
i ++; // Is equivalent to: temp = i++; and so, temp = 3 and then "i" will increment and become i = 4;
System.out.println(i); // Will print 4
Now,
i = 3;
System.out.println(i++);
is equivalent to
temp = i++; // 'temp' will assume a value of the current "i", after which "i" will increment and become i = 4
System.out.println(temp); // We're printing 'temp' and not "i"

Categories

Resources