int [ ] arr = new int[ 4 ]
for(int i = 0; i < arr.length; i++)
arr[ i ] = i + 1
System.out.println(arr[ i ]++)
Printable View
int [ ] arr = new int[ 4 ]
for(int i = 0; i < arr.length; i++)
arr[ i ] = i + 1
System.out.println(arr[ i ]++)
What is your question? What is the problem? What does this code do? What is it supposed to do? Please see the link in my signature on asking questions the smart way.
You decrement exactly how you increment, only with subtraction instead of addition.
Also, I recommend you surround the body of your for loop with curly brackets { }, otherwise you're only executing the single line following the loop.
i did it on purpose..when i use -- it says outofbounds
That JVM is fussy about you're using indexes that go past the end of an array.Quote:
it says outofbounds
Check your code to be sure you do not allow that to happen.
int [ ] arr = new int[ 10 ];
for(int i =8; i < arr.length; i--){
arr[ i ] = i - 1;
System.out.println(arr[ i ]);
this is my code for decrement..but it says "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1"
i want to exit that at 0 hehe
not yet...zzzzzzz
Well, look at your exit condition- it's the second part of the for loop declaration (i < arr.length). The for loop exits when that evaluates to false. But if you're starting at length-1 and only decrementing, that will never be false.
You must read the syntax of the for loop. Kevin has provided you with the best answer. He told you your condition.
So for loop's syntax is actually
Syntax:
And you have successfully done your initialization and iteration (decrement). You have problem in your condition.Code :for(initialization;condition;iteration){ //body of loop; }
You said you want for loop to run till 0.
You are starting from 8. Your array size is 10. You are actually starting from 8 and you are limiting your loop to go till size of array (10).
First time your loop starts, value is 8 that is less than 10, true. Works fine. You decrement one and value becomes 7.... and 6,5,4,3,2,1,0,-1 and so on....
You will never have array index as -1. And this is the problem. Index out of bounds.
Now think and try to solve.
Luck