Control flow logic in for loop - java

How is the following for loop different from original?
Why after initialization, it checks for the condition?
Why such behavior and what are other such tricky behaviors of for loop?
class FooBar
{
static public void main(String... args)
{
for (int x = 1; ++x < 10;)
{
System.out.println(x); // it starts printing from 2
}
}
}
Output:
2
3
4
5
6
7
8
9

++x increments the value of x. As a result, two things are happening:
The value being checked for the for-loop condition (i.e., the inequality), is already incremented, and
This incremented value is what gets printed within the loop.
If you want values from 1 to 9, use the standard loop:
for (int x = 1; x < 10; ++x) { ... }
The effects of prefix and postfix operators has been discussed and explained in detail elsewhere, this post, for example.

The increment of x is combined with the condition. Normally, the increment is performed in the third section of the for loop, which is a statement executed at the end of an iteration.
However, the condition is checked at the beginning of the loop. It's an expression, not a statement, but as you can see, that doesn't stop someone from inserting a side-effect -- the pre-increment of x.
Because x starts out as 1, the condition increments it to 2 before the first iteration.

This is not for-loop trickery, it's the way the prefix and postfix operator works that you're using on x.
++x - Increment x then evaluate its value
x++ - Evaluate the value of x and then increment it.
So, the loop with this definition:
for (int x = 1; ++x < 10;)
executes like this:
Initialize x to 1
Increment x by 1
Evaluate if x < 10. If yes, iterate loop. If no, end loop.
What you want is this:
for (int x = 1; x < 10; x++)
Initialize x to 1
Evaluate if x < 10. If yes, iterate loop. If no, end loop.
Increment x by 1

Each for-loop (except enhanced for loop) has the following structure -
for(initialization; conditionChecking; increment/decrement){
//body
}
Your for-loop also has this structure with the incremetn/decrement portion empty. But to continue the for loop you have to change index (here x) of for-loop. If it is done some how then you can leave the increment/decrement portion empty. If you write the for-loop like this then it also fine -
for(int x=0; x<10; ){
//do something
x++;
}
You also may leave one/more portion (even the body) of a for-loop empty, like this -
int x=0;
for(;x<10;x++); //empty body; do nothing; just increment x

A for loop is valid with one or more of it's some portion leaving empty.
In the your code the increment portion is empty. You have done your increment of index x by using ++x>10. So it is valid. There is no difference from the regular for loop, it's just a way of representing the for loop in different way.

The Original way of a for loop you may have in you mind:
for(initialization; condition; inc/dec/divide..)
And what you mentioned: for (initialization; Inc & check; nothing)
What does it mean? : for(some blaBla; any Bla; some, more, bla)
You may have any expression any where. The Original version is just a convention we follow. Go ahead an write a printing statement or a bitwise operator instead of some blaBla try it out!
Update:
Why :
for (int x = 1; x++ < 10;)
{
System.out.println(x);
}
Prints 2..10? For the answer first try to execute :
for (int x = 1; ++x < 10;)
{
System.out.println(x);
}
It prints from 2..9
You should understand how pre/post fix operators work. x++ in the loop increments the value but not immediately. It increments after x++ < 10;
Where as ++x < 10; first increments and then rest everything happens.
So, when the x value is 9, 9(++)< 10 -> 9 is less ? yeah, now 9++ occurs.It then increments x. but ++x increments 1st so ++9< 10 -> 10<10 NO.

You can write your code as:
x = 1;
while (++x < 10)
{
System.out.println(x);
}
You expect the following:
x = 1;
do
{
System.out.println(x);
}
while (++x < 10);
This is the difference.
The following does what you expect:
for (int x = 1; x < 10; x++)
{
System.out.println(x);
}

TL;DR of it all is that ++x is a pre increment operator. When you use ++x, x will be incremented before any other allied operation. That is why your code prints out 2 first instead of 1 and stops when ++x becomes 10

Related

Finding value of 'i' in a for loop?

I have this question here:
What is i after the following for loop?
The given code is:
int y= 0;
for (int i= 0; i<10; ++i)
{
y+= i;
}
I put that the answer is 9, but that is incorrect according to the grader. I even printed 'i' and it came out as 9.
The answer is that i is undefined after the loop. It is 9 at the last iteration, though.
Value of i would be 10. As of now, if you try to print the value of i outside the loop, i is undefined.
When i was 9, you continued with the loop, for next iteration i became 10 and condition fails and causes to break the loop. So value of i is 10. Keep it in mind having stpe statement as ++i or i++ is not different w.r.t the values that i would attend. step statement always executes before start of the next iteration.
Following small change would help you to prove the output.
int i,y= 0;
for (i= 0; i<10; ++i)
{
y+= i;
}
printf("%d\n",i);
That being said if you are printing the value of i within the loop, then you'll get maximum value of i as 9 on the output. Probably this is what you were doing to conclude the answer as 9.
int y= 0;
for (int i= 0; i<10; ++i)
{
y+= i;
printf("%d\n",i);
}
Think of it this way. Using y+=i is constantly adding the current value of y to the value of i. So, in turn, you're not getting the true value of i, but rather the cumulative value.
This is what is actually happening in y+=i
1+2+3+4+5+6+7+8+9
Also, just printing out i after the loop would be invalid since outside that for loop, i no longer exists.
You could just do this:
int y=0;
for(int i = 0; i<10;i++)
y=i;
System.out.println(y);

Java For Loop Termination Condition: == vs <= vs >=

for (int i = lowerBound; i == upperBound; i++) {
//Code goes here
}
I want the last time the for loop is run to have i equaling upperBound. Is this the right syntax? If so why might one ever use <= or >=?
Thanks in advance. :)
A for loop can always be translated to a while loop as follows:
for(initialization; condition; step) {
block;
}
To
initialization;
while (condition) {
block;
step;
}
So if your condition is i == upperBound, the loop will never run, because the condition doesn't start out as true. <= will do what you want, though.
for (int i = lowerBound; i == upperBound; i++) {
//Code goes here
}
The part inside for loop executes when it checks the constraint/condition mentioned inside for loop statement.
Example
for( int i =0; i == 10 ; i++){
saySomething();
}
will run only when i == 10 ie i would have been i=10 , while if you had written i<10 or i<=10 it would have run each time that condition is true.
Here is a quick example : link for for loop.
To run all + equals to upperBound, you need to use <=
One may might use >= if you're counting backwards, <= and if you're counting forwards.
Use:
i <= upperBound
inside the loop.
The reason being that the loop is testing against all constraints in that loop and will only run when it ticks these off as being true. i is only equal to upperbound in one case and never while i it is also equal to lowerbound, so it won't run.
(Eek. First ever answer here! I hope this helps!)

Translate for loop to a while and do while loop in Java

I created a couple for loops that print lines as such (each new number starts a new line, it doesn't show here):
1
22
333
4444
etc. until it reaches 9 then goes back down to 1.
I am supposed to translate it into both a while and do while loop and have been trying for the past hour and can't seem to do it.
public static void main(String[] args) {
for (int x=1; x <= 9; x++) {
for (int y = 1; y <=x ; y++){
System.out.print( x + "");
}
System.out.println();
}
// TODO code application logic here
for (int x=9; x >=1; x--) {
for (int y = 1; y <=x ; y++){
System.out.print( x + "");
}
System.out.println();
} int y =1;
int x = 1;
while (x <9){
while (y <=x){
y++;
System.out.print(x +"");{
}
System.out.println();
}
x++;
}
A for loop statement has three parts in the for (init; condition; post). These parts are separated by semicolons. The init part specifies an initial statement, the condition is what determines if the loop body is executed or not and the post specifies a post loop statement.
You can do the same thing with a while loop except that instead of a single statement, it is actually several statements. However a while loop is not exactly like a for loop since the continue statement and how it behaves is a concern. More about that later.
A hint is that the various parts of the for statement are separated by semicolons which are also used to separate statements in Java.
Consider the following for loop source example.
int i;
for (i = 0; i < 5; i++) {
// for loop body
}
So you would have an init statement before the loop statement, i = 0 then the loop statement itself containing the condition, i < 5, and as the last line in the loop before the closing curly brace, you would put the post loop condition, i++.
The do while is a bit more complicated because of when the while condition is evaluated. In both the for loop and the while loop, the condition is evaluated and if the expression is not true then the loop body is not executed at all, it is skipped. In the case of the for loop, the init statement is executed and then the condition is evaluated to determine if the for loop body should be executed. Since a while loop does not have an init statement as part of the while statement, the condition is evaluated and if not true, the while loop body is not executed.
A do while loop has a condition that is not evaluated until after the first time through the do while loop body. So the statements within the do while loop are always executed at least once. Then the do while condition is evaluated and if true, execution returns to the top where the do is and the do while loop body is executed again.
Some code of several variations of loops where the init is i = 0 and where the condition is i < 5 and the post is i++. In all cases I have the variable i defined out side of the loop body. In the case of a for loop, defining the variable i within the for statement causes the scope of the variable i, its visibility, to be restricted to the for loop body which would not be the case for the other types of loops.
int i;
for (i = 0; i < 5; i++) {
// for loop body
}
int i = 0;
while (i < 5) {
// while loop body
i++;
}
int i = 0;
do {
// do while loop body
i++;
} while (i < 5);
I mentioned that what happens when the continue statement is executed can make a difference when comparing these forms of loops. The way to think of it is that when a continue statement is executed then there is a jump to the closing brace of the loop statement enclosing the continue statement. So this introduces something to consider.
Look at the above examples but with a continue statement. In all of the examples below there is a continue statement which causes execution to skip to the end of the loop body when the variable i has a value of 3.
With this change the for loop will continue incrementing the variable i because it's post, the third part of the for statement, is executed at the end of the loop. However with the while loop and the do while loop, the incrementing of the variable i is part of the loop body so when the continue is executed skipping to the end of the loop, the increment of the variable i is also skipped.
int i;
// first time init variable i to zero then evaluate condition
for (i = 0; i < 5; i++) { // evaluate condition and execute loop body if true
// for loop body
if (i == 3)
continue; // when i == 3 continue is executed to skip to end of loop
} // at point of braces, post executed, condition evaluated
int i = 0;
while (i < 5) { // evaluate condition and execute loop body if true
// while loop body
if (i == 3)
continue; // when i == 3 continue is executed to skip to end of loop
i++; // variable i only incremented when this statement is executed
} // braces indicate end of loop so jump back to top of loop
int i = 0;
do {
// do while loop body
if (i == 3)
continue; // when i == 3 continue is executed to skip to end of loop
// more statements which may be skipped by the continue
i++; // variable i only incremented when this statement is executed
} while (i < 5); // evaluate condition and jump to top of loop if true
You could make a change to the do while loop while condition to move the incrementing of the variable i into the while condition evaluation by using a pre-increment operator, the ++ operator, on the variable as in the following. We use the pre-increment operator because we want to increment the variable i before we check its value.
int i = -1; // need to start at -1 since the while will increment at beginning of the loop
while (++i < 5) { // increment variable i, evaluate condition and body of loop if true
// while loop body
if (i == 3)
continue; // when i == 3 continue is executed to skip to end of loop
} // braces indicate end of loop so jump back to top of loop
int i = 0;
do {
// do while loop body
if (i == 3)
continue; // when i == 3 continue is executed to skip to end of loop
// more statements which may be skipped by the continue
} while (++i < 5); // increment variable i, evaluate condition and jump to top of loop if true
Try this as your while loop:
int y = 1;
int x = 1;
while (x < 9) {
y = 1;
while (y <= x) {
y++;
System.out.print(x + "");
}
System.out.println();
x++;
}
A for loop is a construct that is extremely similar to a while loop, except that it provides some extra niceties that reduce boilerplate code.
The beginning of a for loop sets your initial variable (in your case, x), your condition clause (x <= 9) and your incrementor (x++). A while loop does not do these things for, it simply runs a block of code while the condition clause in the () is met.
Converting a for loop to a while is simple-
for(int x = 0; x < 10; x++) {
int x = 0;
while(x < 10) {
x++;
}
The while loop has all the same features as the for loop, but without the syntactic sugar. This should help you convert the loops in your question, and in general.

Java Changing For to While

I would like to change this for loop to a while statement:
for (int x = 0; x < items.size(); x++) {...}
I've tried:
int x = 0;
while(x<items.size()){
x++;
...
}
but it won't work.
put the x++ at the end of the while block.
while(x<items.size()){
...
x++;
}
It should be
int x = 0;
while(x<items.size()){
...
x++;
}
With the x++ in the end of the loop (because in the for loop, the increment section is executed only after the program control reaches the closing braces), but otherwise everything looks ok. It should work.
Your code should have been as follows,
int x = 0;
while(x<items.size()){
...
...
...
x++;
}
The reason for x++ operation to be the last statement in the loop is to increment the value of 'x' only when we are done with the loop and we need to increment the value of looping variable.
If you put x++ in the starting of looping code, the code will not work for the last looping scheme, wherein, prior to entering the loop, the value of x would have been x=items.Size( );. So it wouldn't be able to enter the loop as the condition is x<items.Size();

Does a for loop's while section execute each pass or only once in java?

for example would this be constant or change with each pass?
for(int i = 0; i < InputStream.readInt(); i++)
for(int i = 0; // executed once
i < InputStream.readInt(); // executed before each loop iteration
i++ // executed after each loop iteration
) {
....
}
The first section is executed once before the looping starts. The second section is checked before every loop and if it is true, the loop gets executed, if false the loop breaks. The last part is executed after every iteration.
It executes every time. The for syntax is sugar for
int i = 0
while(true)
{
if(!(i < InputStream.readInt()))
{
break;
}
// for body
i++
}
For times when a control-flow diagram is actually the best graphical representation of a concept.
http://upload.wikimedia.org/wikipedia/commons/0/06/For-loop-diagram.png
I think the main issue is the question: does
i < InputStream.readInt();
get executed each loop iteration? Yes, it does.
In this case it's not changing any sensitive variable, the only variable actually changing in your code is i, but InputStream.readInt() will be run each iteration to make the comparison and will therefore run readInt() again on InputStream.
What about something like:
for (int i=0; i < xObj.addOne().parseInt(); i++)
(given the method addOne returns a string representation of an integer one greater)
Is my "check" incrementing the value that would be incremented if I called xObj.addOne() like normal? Yes. and does it stay incremented to the next loop iteration? Yes.
It's just like doing
int x = 0;
for (int i=0; i < ++x; i++);
This will never terminate, as ++x is always greater than x (which is also i)
What about a nontrivial example?
int x = 6;
for (int i=0; i < x--; i++) {
System.out.print(i+" ");
}
outputs
0 1 2

Categories