Click here to Skip to main content
15,890,845 members
Please Sign up or sign in to vote.
1.22/5 (2 votes)
See more:
Hi, I guess it's really silly question but:
why --> for (int i = 1000; i >=1; i-=2) System.out.println(i); (Cmd prints i)

---> for (int i = 1000; i <=1; i-=2) System.out.println(i); (no errors, no printing on the screen)

Why when i input <= cmd doesn't react and don't display decreasing iteration ?

Thank you in addvance!

What I have tried:

for (int i = 1000; i <=1; i-=2)
for (int i = 1000; i <1; i-=2)
Posted
Updated 13-Sep-18 6:12am
Comments
Bryian Tan 13-Sep-18 11:34am    
think about it, initially, i will be 1000, there no way 1000 < 1

for (int i = 1000; i <=1; i-=2)
for (int i = 1000; i <1; i-=2) 



Look at your code. You start off with i<1 being false so it does nothing

When you use the >= version, you don't abort immediately.

You need to rethink about the order for the inequality!
 
Share this answer
 
Comments
Member 13983435 13-Sep-18 12:02pm    
In both cases cmd doesn't print nothing
for (int i = 1000; i <=1; i-=2)
for (int i = 1000; i <1; i-=2)
...and I wonder why?
What I realize is that when we have i++ need to use < and when i-- we need to use > sign. Only then the program is printed .
But I still don't understand why exactly.
Dave Kreskowiak 13-Sep-18 12:16pm    
You're just following a visual pattern, but you have no understanding of what each piece of the "for" statement does.

A "for" statement says this:
    for( initializer; bail out condition; step )

Using your 1st loop as an example:

1. Start with i having a value of 1000.
2. If i is less than or equal to 1, run the code in the loop, otherwise exit the loop.
3. When the code in the loop is finished, decrement i by 2.
4. Go back to step 2.

The loop doesn't do anything because i is greater than 1. The code in the loop is never executed.

Your second loop:
1. Start with i having a value of 1000.
2. If i is less than 1, run the code in the loop, otherwise exit the loop.
3. When the code in the loop is finished, decrement i by 2.
4. Go back to step 2.

Same problem. The value of i is greater than 1, not less than, so the code in the loop is never executed.
Member 13983435 13-Sep-18 12:19pm    
I didn't know the loop works like that :) now I know and thank you so much for that
First, study this Flow of Execution of the for Loop[^]
in the case of
for (int i = 1000; i <=1; i-=2) System.out.println(i); 

1. Initialization: i is initialized to 1000, i.e. i=1000, then it proceeds to 2;
2. Condition: the outcome of i <= 1, i.e. 1000 <= 1, is False, exit the loop, as such
System.out.println(i);
will never be executed.
 
Share this answer
 
Comments
Member 13983435 13-Sep-18 12:15pm    
I see, that make sense
Thank you very much for the quick response (Y)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900