Results 1 to 3 of 3
Thread: incrementing array elements
- 10-06-2010, 01:54 PM #1
Senior Member
- Join Date
- Mar 2009
- Posts
- 105
- Rep Power
- 0
incrementing array elements
OK this one is more me asking someone to explain this to me because it doesn't seem intuitive at all:
I encountered some code today that looked sort of like this:
The bold section of code is that part I didn't know about. Why is it that 'pos' is incremented only after the assignment is done?Java Code:int[] array = new int[5]; int pos = 0; int value = 1; for (int i = 0; i < array.length; i++) { [B]array[pos++] = value;[/B] value++; } for (int i = 0; i < array.length; i++) System.out.println("element " + i + " with value="+array[i]);
It seems to me like it should be the other way around. That 'pos' should increment first and then the assignment should happen. This would mean that in the first iteration pos would increment to 1 and the first value would instead be assigned to element [1] in the array not [0].
Why does it increment afterwards?Last edited by porchrat; 10-06-2010 at 01:57 PM.
- 10-06-2010, 01:58 PM #2
Senior Member
- Join Date
- Jun 2008
- Posts
- 2,366
- Rep Power
- 7
That is called the post increment operator, which means the original is value is evaluated in that position. As soon as it is evaluated, the value is then incremented.
If you want it incremeneted first then you need pre increment operator, i.e.
rather thanJava Code:++pos
.Java Code:pos++
- 10-06-2010, 02:37 PM #3
Senior Member
- Join Date
- Mar 2009
- Posts
- 105
- Rep Power
- 0
Similar Threads
-
incrementing elements in an array
By JavaNubb in forum New To JavaReplies: 7Last Post: 08-20-2010, 03:15 AM -
sum of elements in array
By myst in forum New To JavaReplies: 7Last Post: 07-17-2010, 08:36 AM -
How array elements gets default value
By Veangat in forum New To JavaReplies: 1Last Post: 03-07-2010, 01:29 PM -
Looping Array Elements
By enzyme in forum New To JavaReplies: 3Last Post: 11-26-2009, 04:35 PM -
Help with array of elements
By zoe in forum New To JavaReplies: 1Last Post: 07-24-2007, 05:33 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks