public class example1 { public static void main( String args[] ) {
int numarray[] = new int[10];
for (int indx = 0; indx < 5; indx++) {
numarray[indx + 2] = indx + 1;
}
System.out.println(numarray[4]); }
}
forgive my ignorance, but i cant work out the line:
numarray[indx + 2] = indx + 1;
when i insert a system.out.print line inside the for loop it shows me all the values in the array. these are (0, 0, 1, 2, 3) so the numarray[4] value is obviousley 3. but how can there be 2 leading 0's in the array? i think i must be reading the line (numarray[indx + 2] = indx + 1;) totally wrong.
could anyone please step through the line of code, I would greatly apperciate it. again sorry about the 'level' im at, but i guess i got to start some where :)
you create an array of length 10 of int values. numarray[0] numarray[1] numarray[2] numarray[3] numarray[4] numarray[5] numarray[6] numarray[7] numarray[8] numarray[9]
The default value of a int variable is 0, so initially each array element is 0.
when indx is 0, numarray[2] is set to indx+1 or 1 when indx is 1, numarray[3] is set to indx+1 or 2 when indx is 2, numarray[4] is set to indx+1 or 3 when indx is 3, numarray[5] is set to indx+1 or 4 when indx is 4, numarray[6] is set to indx+1 or 5
then the for loop exits
and the line
System.out.println(numarray[4]);
executes giving 3
now your array values are: numarray[0] is still 0 numarray[1] is still 0 numarray[2] is 1 numarray[3] is 2 numarray[4] is 3 numarray[5] is 4 numarray[6] is 5 numarray[7] is still 0 numarray[8] is still 0 numarray[9] is still 0