Results 1 to 4 of 4
Thread: For loop using i++ and ++i
- 04-30-2012, 04:50 PM #1
Member
- Join Date
- Nov 2011
- Posts
- 56
- Rep Power
- 0
For loop using i++ and ++i
Okay, this has been bothering me for the longest time possible.
I'm not exactly a new to java, and I understand the post and pre increment, but this for loop thing has been bothering me like forever.
Okay, so i++ returns the value before it is incremented, right?Java Code:public class Testing { public static void main(String[] args) { for (int i = 0; i < 2; i++) { int k = i; System.out.println(k); } } }
So basically,
1) I declare i = 0. i(0) is < 2, so I enter the for loop.
2) k = i(0)
3) I print out 0.
4) i++;
Shouldn't i still be a 0? Since it returns the value before it is incremented? Wow, I can't believe I'm so bothered by this, but I'll be grateful if anyone could enlighten me.
- 04-30-2012, 05:05 PM #2
Re: For loop using i++ and ++i
You aren't using the value returned by the ++ operator at all. Try something more like this:
Java Code:int i = 0; while(i < 10){ System.out.println("i before i++ is: " + i); System.out.println(i++); System.out.println("i after i++, before ++i is: " + i); System.out.println(++i); System.out.println("i after ++i is: " + i); }How to Ask Questions the Smart Way
Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!
- 04-30-2012, 05:08 PM #3
Member
- Join Date
- Nov 2011
- Posts
- 56
- Rep Power
- 0
Re: For loop using i++ and ++i
Oh, I see. That explains it. Because I thought that when you are comparing i<2, you were using the return value of i++; Thanks for your code. I'll read it up later. :)
- 04-30-2012, 05:47 PM #4
Re: For loop using i++ and ++i
No. The increment expression is invoked after each iteration of the loop. Please read this: The for Statement (The Java™ Tutorials > Learning the Java Language > Language Basics)
How to Ask Questions the Smart Way
Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!
Similar Threads
-
Problem with while loop, assigning a variable with a different value every loop? Help
By JavaProg in forum New To JavaReplies: 2Last Post: 11-07-2011, 02:25 AM -
Is it Possible? Array elements Initialized in Loop, can it be viewed outside loop?
By JPH in forum New To JavaReplies: 1Last Post: 10-01-2011, 02:12 AM -
JTextField loop 2x for-loop WEIRD!
By Streetproject in forum AWT / SwingReplies: 2Last Post: 02-16-2011, 05:46 PM -
[Q] Loop issue (while loop)
By iriscience in forum New To JavaReplies: 9Last Post: 01-31-2011, 04:21 PM -
How can I rewrite the following while loop using a for loop?
By gt11990 in forum New To JavaReplies: 5Last Post: 04-30-2010, 05:05 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks