I've been scratching my head over why Java will go beyond a specified condition in some loops, while seemingly adhering to the condition in other loops. I know it's a lack of understanding on my part, but I'm confused as to when I should go over or adhere to the condition when I'm manually calculating code.
As an example, I've put in a short for loop which has an end result of 15 in iTotal, and 0 in iNumber. When I originally did the calculation on paper step by step, I ended up with the answers of 14 in iTotal, and 1 in iNumber. I assumed that the code would not go below one, as the condition was greater than zero, not equal to or greater than zero.
My original attempt -
iTotal
0
5
9
12
14
iNumber
5 4 3 2 1
int iTotal = 0;
for (int iNumber = 5; iNumber > 0; iNumber--)
iTotal = iTotal + iNumber;
In comparison, the below code snippet will at 19 with a condition of less than 20, with the last statement being value of x : 19. I calculated that correctly, but I'm not sure why the above code ignores the condition and goes to zero, while the below code adheres to the condition and stops at 19.
for(int x = 10; x < 20; x = x+1) {
System.out.print("value of x : " + x);
System..out.print(num2 + " " + num1);
Could anyone clarify how java interprets when to go over or stop at specified conditions?
In comparison, the below code snippet will at 19 with a condition of
less than 20, with the last statement being value of x : 19. I
calculated that correctly, but I'm not sure why the above code ignores
the condition and goes to zero, while the below code adheres to the
condition and stops at 19.
What you said is incorrect. The last statement printed is 19 but the last value of x is 20. This loop that you have given does in fact execute 20 times. A for loop in Java like the one you given has 3 components an integer to use as a count, a condition to test, and how to transform the count variable. In a general form it looks like this:
for(count variable, condition, transformation){
//Code goes here
//End loop
}
This for loops executes until the condition is no longer true, which is caused by applying a transformation of some sort the count variable.
Using the for loop you gave as an example:
for(int x = 10; x < 20; x = x+1) {
System.out.print("value of x : " + x);
System..out.print(num2 + " " + num1);
}
We create the count variable (int x) and set it equal to 10.
We check the count variable (int x) against the condition ( x<20 ) and evaluate the result, x < 20 == true so the code within the loop is run. At the end of the code, which I have marked "End Loop" above the transformation (x + 1) is applied to the count variable before the condition is tested again to see if the loop should proceed.
x = 11 now because x was equal to 10 but we added one as specified at the end of last loop. x < 20 == true is still true so the code within the loop will be executed again. This is continued in this way until the last number.
When x = 19 we test against the condition as we have been doing and see if x < 20 == true is still true, which it is so the code is executed. When the code execution ends, the count variable is again incremented, so x = 20.
With x = 20we once again test against x < 20. This time x < 20 == false so the code inside the loop is not executed nor is another transformation applied to the variable. At this point, when the condition becomes false the loop ends. So because we said x < 20 and not x <= 20 on the 20th loop, when x = 20, this code:
System.out.print("value of x : " + x);
System..out.print(num2 + " " + num1);
will not run. This means that the final output of the program would occur when x = 19 not when x=20 although if you were still able to access the count variable after the loop ends (which I believe you can do with a debugger) you would see x=20
The first loop does this:
iTotal = 0
iTotal = 5
iTotal = 9
iTotal = 12
iTotal = 14
iTotal = 15
Loop end
also as the first loops transformation is written as x-- instead of x - 1 the second loop can be rewritten as:
for(int x = 10; x < 20; x++) {
System.out.print("value of x : " + x);
System..out.print(num2 + " " + num1);
}
in Java the ++ operator increments by 1, it is the same as x+1.
Your first loop
for (int iNumber = 5; iNumber > 0; iNumber--)
iTotal = iTotal + iNumber;
is 5+4+3+2+1 = 15 (you must have printed iTotal before you added the first iNumber). Your second loop is similar the loop body isn't entered when the condition evaluates to false.
int x = 10;
for(; x < 20; x = x+1) {
System.out.print(x + " ");
}
System.out.println(x); // x is 20
as 10,11,12,13,14,15,16,17,18,19,20 but at twenty the loop terminates.
The condition is checked before each loop, not after. So in your first example, the logic would go:
iNumber = 5
first loop iteration
check iNumber > 0. 5 > 0, so continue the loop
add 5 to iTotal (iTotal=5 after this)
decrement iNumber
second loop iteration
check iNumber > 0. 4 > 0, so continue the loop
add 4 to iTotal (iTotal=9 after this)
decrement iNumber
...
fifth loop iteration
check iNumber > 0. 1 > 0, so continue the loop
add 1 to iTotal (iTotal=15 after this)
decrement iNumber
sixth loop iteration
check iNumber > 0. 0 > 0 is false, so break out of the loop
A similar process happens with the second loop.
Related
Does this for loop ever stop?
for(int i=1; 1/i > 0; i++) {
}
If so, when and why? I was told that it stops, but I was given no reason for that.
Yes.
First iteration: i = 1, 1/1 = 1 > 0, so it loops.
Second iteration: i = 2, 1/2 = 0 !> 0 (integer division), so it stops.
First iteration: i =1, 1/1 equals 1 so continue.
Second iteration: i = 2 , 1/2 equals 0 as it is integer division, so condition is false and it stops.
Details about integer division are documented in javadoc
Yes the for loop stops after one iteration. Dividing 1 by 2 in the second iteration will cause the for loop to stop because intergers don't record decimals meaning one divided by two will be 0 rather than .5.
1/2 is evaluated as an integer, and simply chops the decimal point. Hence 1/2 = 0.
If one of those numbers was a floating point (ex. 1.0/2 or 1/2.0), it would return the expected 0.5.
in this code
for(int i=1; 1/i > 0; i++) {
//any code here
}
in your code
set the condition the number larger than 0
the counter start from 1 (integer number)
first run for loop cheek condition 1/1 > 0 => true the code execute.
after first run the counter increment by 1 .
after that the for loop cheek condition 1/2 > 0 => false the not execute and for loop stop
why the for loop stop in 1/2 because 1 integer and 2 integer
and integer / integer must = integer 1/2 = 0 (0.5 not integer)
if you use this code the for loop many many executed .
because int/float = float
1/1.0 =1 / 1/2.0= 0.5 / 1/3.0 = 0.33333 / 1/4.0 = 0.25 ...ect
for(float i=1; 1/i > 0; i++) {
//any code here
}
this is my first time posting and I am definitely a novice so if I provide incorrect information someone please correct me :).
My understanding is that because i and 1 are both of the type integer in the line:
for(int i=1; 1/i > 0; i++)
then your program will automatically perform integer division/arithmetic which results in the modulus or remainder being dropped. Therefore during the second iteration the remainder of 0.5 will be dropped resulting in 0 and thus termination of the loop.
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.
I am attempting to write a code in Java to take a word and scramble it. I have a for loop to loop through the word:
String inWord = getWord.nextLine();
//loop as many times as x < length of word
for(int x = 0; x >= inWord.length(); x++){
//random number between 0 and length of word - 1
int randomChar = randChar.nextInt(inWord.length() - 1);
out.print("in the first for loop, randomChar is equal to " + randomChar + ", and x is equal to " + x);
The loop continues with some other irrelevant code, then is closed. However, when run, the console only takes a word as input then terminates the program. Nothing is printed. Is something wrong with my for loop?
You have switched the for-loop condition, it should be:
for (int x = 0; x < inWord.length(); x++) {
Note that the second part of the loop, here x < inWord.length() is the condition for when the loop should run, not when the loop should break. The loop runs as long as that condition is true.
Additionally,
int randomChar = randChar.nextInt(inWord.length() - 1);
Should be:
int randomChar = randChar.nextInt(inWord.length());
Otherwise you won't have a chance of returning the last character in the string.
Random.nextInt(int bound) documentation says:
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)
You initialized x to 0 in the first part of your for loop, then in your conditional, you checked to see if it's greater than or equal to the word length (x >= inWord.length()). Since that condition is almost never met (i.e. the word has to be length 0, which will almost never happen) the loop won't be entered. You probably meant x < inWord.length() instead.
Yes, your operator is reversed, use <.
I understand how mostly everything works in a loop in Java but I came to a realization that I am failing to understand one thing which is The Order a Loop Operates.
Basically I am failing to understand this because of this simple but boggling piece of code that was displayed in my class, the code is displayed below.
public class Test {
public static void main (String[] args) {
int sum = 0;
for (int k = 1; k < 10; k += 2)
{
sum += k;
System.out.print(sum + " ");
}
}
}
The output the program puts out is 1 4 9 16 25
Now I understand how it repeats and spits out the numbers but how does it go about even creating 1. Now you can say it created 1 by taking k and adding it to sum but shouldn't k be equaling 3?
It goes k = 1; This sets k equal to 1. k < 10; Checks if k is less than 10. Then the question is when k += 2; Shouldn't k now equal to 3 but instead sum is now somehow equal to 1 after this operation occurred of adding 2 to 1, 2 + 1 = 3 but 3 + 0 = 1? How does this even go about.
My rationalizing for this is that any program I thought was to interpret code line by line or uniformly and not jumping around.
Overall my question is, how is sum equal to 1 when k is actually equal to 3.
The sections of the for loop are run at different times.
The first section is run once at the start to initialize the variables.
The second is run each time around the loop at the START of the loop to say whether to exit or not.
The final section is run each time around the loop at the END of the loop.
All sections are optional and can just be left blank if you want.
You can also depict a for loop as a while loop:
for (A;B;C) {
D;
}
is the same as:
A;
while (B) {
D;
C;
}
Let's step through your code:
We setup an int with initial value of 0 and assign it to sum.
We setup a for loop, setting int k = 1, and we will loop while k is less than 10, and after each iteration, 2 will be added to k.
So, the first iteration, k = 1. sum currently equals 0, so sum += k is actually 0 = 0 + 1 = 1. There's the 1 you are getting.
For the second iteration, k = 3. sum currently equals 1, so sum += k is actually 1 = 1 + 3 which is 4. There's the 4 that is showing up.
Repeat this for the rest of the loop!
In the first iteration of the loop, k=1. The k+=2 is only run at the beginning of the next iteration of the loop. The loop variable update condition (the last part of the for loop - i.e. the k+=2 part) never runs on the first iteration but does run on every other one, at the start. Therefore what you have is:
Iteration 1:
k=1
sum = 0 + 1; //so sum = 1
Iteration 2:
k=1+2 // so k=3
sum = 1 + 3 // so sum = 4
Iteration 3:
k=3+2 //k=5
sum = 4 + 5 //sum=9
etc...
It goes like this:
Initialize (k = 1)
Check condition (k < 10) (stop if false)
Run the code in the loop (sum += k and print)
Increment (k += 2)
Repeat from step 2
Following this logic, you get that 1 is printed first.
The last condition, k += 2 occurs after the first iteration of the loop.
So it's
k = 1, sum = 1
k = 3, sum = 4
k = 5, sum = 9
k = 7, sum = 16
k = 9, sum = 25
k is only incremented after the loop iteration. In general for any loop the values are updated after a loop iteration so k goes 1,3,5,7,9 and so the sum is correct.
Oh believe I had same problem. And you have to understand this quickly because when you are going to start doing bubble sort it will confuse you even more.
The thing you need to understand is that, its that it doesnt actually add +2 to 'k' until its done reading whats inside your 'for loop'
So this is how it starts, its starts with what you set 'k' for which is 1.
k = 1 is it less than 10? Yes, then do whats in the 'for loop' . Sum at first was initiated to 0. then in the first loop we add the value of k to whatever sum already has. So
sum = 0, k = 1. Therefore 0 +1 = 1. then next line ouput the value of sum with space. AND here is the IMPORTANT PART, it has now reach the end of the loop. So now it will add +2 to the value that k already has.
So k = 1 + 2 = 3. And now we start the second loop.
k=3, is less than 10? yes, ok do whats in for loop. add k to whatever value that sum already has. Sum is = 1 right ? and k is now equal to 3 right? So 3 + 1 = 4. And it display sum with a space and it has reach the end of the for loop so it add +2 to k that already has 3 in it which will equal to 5. and the loop continues.
oouff hope that helps! So remember it adds +2 at the end of the loop. Sorry if theres some typos typing from my samsung kinda annoying a bit cuz i have japanese keyboard...
Good luck!
has to
Let's break up your code. The keyword for just means loop. It will start # 1 and continue as long as k is less than 10. It will also increase by k+=2. To translate, it means k = k +2
Inside the loop sum = sum + k. It will then print the value that sum has plus a space.
k = 1, sum = 1
k = 3, sum = 4
k = 5, sum = 9
k = 7, sum = 16
k = 9, sum = 25
and keep repeating. Let me know if you still have trouble grasping this concept
int x = 10;
x += x++;
System.out.println(x);
why the answer of above statement is 20 ?
The operator += is an addition assignment operator. Like Alya said above, x += x++ is equivalent to x = x + x++, which in your case is x = 10 + 10. However, it's a very messy statement and I'll explain why towards the end of this post.
Now, you're probably thinking "Why is it 20 and not 21 (10 + 11) since you have the ++?" and that's valid. There's actually a difference between a post-increment and a pre-increment. x++ is the post-increment and will actually evaluate the value of x first and THEN increment x, while ++x is the pre-increment which will increment x and THEN evaluate the value of x.
For example, x = 10; System.out.println(x++); System.out.println(x); will print 10 and then print 11 because the first print line prints x and THEN performs the ++ calculation, making x 11 which the next line prints. Conversely, x = 10; System.out.println(++x); System.out.println(x); will print 11 on both print statements.
Going back to why I said x += x++; is very messy is because technically the ++ operator isn't performed in this case. x++ is technically the same as x=x+1 and remembering that x+=y is the same as x = x+y) , the line x += x++; is kind of like saying x = x + (x = x + 1); which is kind of weird looking because you do 2 assignment statements in one and won't actually "work how you want it". Back to your example int x = 10; x += x++; if you print x, you will get 20 even though you could look at it as: x is now the value of x + the value of x, then finally + 1 to it. But unfortunately, that's not how it works.
To solve your problem, if you change your code from a post-increment to a pre-increment, then it should work, ie: x+=++x; will print your 11 but I would argue the that's quite unreadable and a bit confusing. x+=x; x++; System.out.println(x); is easier to follow.
x++ will execute first. It returns x and then increments x by 1.
Finally, the += operator will add to x the return value of x++, which was 10.
Thus, x will be 20 and it will overwrite the changes to x by the statement x++.
So first x is initialized to be 10. Then the x++ has higher precedence so that gets carried out first. the "++" is a post-increment in this case (because it is after the variable as opposed to pre-increment which would be ++x). Post-increment means "first use the variable then increment it by one" so in this case it first uses x to be 10 then increments it to 11 after it is used. Then we look at the "+=" which is short hand for "x = x+x++". so we have x = 10+10 which = 20. If you were to carry this out again it would equal x = 20+20 = 40.
In this particular case, the x++ isn't necessary as x is reassigned the value after it is incremented each time.
int x = 10; x += x++;
will equal to x=x+x
where x++ mean use the x value then increament it , so it's value will be 10
so the result will equal 20
if you want to see the change of the x , see this example:
int x = 10;
int y = 10;
y +=x++;
System.out.println(y);
System.out.println(x);
will print :
y=20
x=11////////////according to x++ and without to overwrite it
//
// Shows how increments work.
//
int i = 0;
System.out.println(i);
i++; // Add one
System.out.println(i);
i += 2; // Add two
System.out.println(i);
i += 3; // Add three
System.out.println(i);
++i; // Add one
System.out.println(i);
i += i; // Added itself
System.out.println(i);
//
// Uses increments and assigns.
//
int v = 0;
v = i++; // Increment after value copy
System.out.println(v);
System.out.println(i);
v = ++i; // Increment before value copy
System.out.println(v);
System.out.println(i);
//Output
0 -
1
3
6
7
14
14
15
16
16
x+=x++ first assigns the value to x and then increments (post-increment)
x+=++x first increments then assign the value to x (pre increment)
there are two types of increments/decrements in programming
1. pre-increment/decrement
2. post-increment/decrement
In programming both of these have same operations but differ in there nature as they both used for increment or decrement; they can be written as,
x+=1; (increment by 1)
x-=1; (decrement by 1)
you can use a variable instead in the above cases as well