int month = months[4]; //get the 5th month (May)Most of the times it is not known in the program that which elements are of interest in an array. To find the elements of interest in the program, it is required that the program must run a loop through the array. For this purpose "for" loop is used to examine each element in an array. For example :-
String months[] =Here, we have taken an array of months which is,
{"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"July", "Aug", "Sep", "Oct", "Nov", "Dec"};
//use the length attribute to get the number
//of elements in an array
for (int i = 0; i < months.length; i++ ) {
System.out.println("month: " + month[i]);
String months[] =Now, we run a for loop to print each element individually starting from the month "Jan".
{"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"July", "Aug", "Sep", "Oct", "Nov", "Dec"};
for (int i = 0; i < months.length; i++ )
In this loop int i = 0; indicates that the loop starts from the 0th position of an array and goes upto the last position which is length-1, i < months.length; indicates the length of the array and i++ is used for the increment in the value of i which is i = i+1.
No comments:
Post a Comment