Originally Posted by
hemla
when is i=0 and i=1 used? how do i know when to use 0 or 1?
Here is a basket. There are 10 eggs in the basket.
The computer sees egg numbers 0, 1, 2, 3, 4, 5, 6, 7, 8, 9; you start with zero
The program is to print out stickers to number the eggs for a party. You want 1, 2, 3, 4, 5, 6, 7, 8, 9, 10; you start with 1
But as far as your code sample:
for(i=0;i<numbers.length;i++)
For the egg example a println on numbers.length would print 10. In the above for loop i would be 0 on the first iteration and 9 on the last iteration that executed the body of the loop, and 10 on the cycle that exits the loop. So in a sense they are 1 through 10 as people count them, but the computer counts them 0 through 9.
Consider the egg samples:
//Note i=0 and the use of <
for(i=0;i<eggsInBasket;i++) {
//println: This is egg number i+1;
}
//vs the following loop using i=1 to do the same:
//Note i=1 and the use of <=
for(i=1; i<=eggsInBasket;i++) {
//println: This is egg number i;
}
In the first loop you have to add 1 to i to print 1-10 rather than 0-9.
In the second loop you print 1-10 without that addition.
Rather than use i=1 you sometimes see something like:
for(int i=0; i<eggsInBasket; ) {
System.out.println("This is egg number: " + ++i);
}
...where the loop is controlled within the body being executed.