Looping Arrays Tutorial

From Progzoo
Jump to: navigation, search

You can use a for loop to access each element of an array. There are two different styles of for loop. One uses an index the other does not:

"for-each"

This kind of for loop does not use an index. It is simpler and more readable. Use this style of loop wherever possible.

int [] list = {1,2,3};
for (int v:list)
  System.out.println( v );

Indexed loop

You use this kind of for when you need to get to the index. The later questions in this section use this style.

for (int i=0;i<list.length;i++)
  System.out.println( list[i] );

Print Double Every Item

Print twice the value for each item of the array.

For the array [2, 7, 5, 3] you should print:

4
14
10
6


[Font] [Default] [Show] [Resize] [History] [Profile]

Print Every Item Twice

Print the value twice for each item of the array.

For the array [2, 7, 5, 3] you should print:

2
2
7
7
5
5
3
3


[Font] [Default] [Show] [Resize] [History] [Profile]

Print Every Item Two Times

Print the value two times on the same line for each item of the array.

For the array [2, 7, 5, 3] you should print:

22
77
55
33


[Font] [Default] [Show] [Resize] [History] [Profile]

Print Every Item Times the Index

For each item print the value times the index.

For the array [2, 7, 5, 3] you should print:

0             0*2
7             1*7
10            2*5
9             3*3


[Font] [Default] [Show] [Resize] [History] [Profile]

Print the Index and the Item

For each item print the index and the value.

For the array [2, 7, 5, 3] you should print:

0 2
1 7
2 5
3 3


[Font] [Default] [Show] [Resize] [History] [Profile]

Print the Index and List Backwards

Print the index and list backwards.

For the array [2, 7, 5, 3] you should print:

0 3
1 5
2 7
3 2

The expression x[x.length-i-1] will get you the index "backwards". So if i goes 0 1 2 3 then x.length-i-1 will go 3 2 1 0


[Font] [Default] [Show] [Resize] [History] [Profile]

Print the List and the number of Succeeding Items

Print each item followed by the number of remaining items.

For the array [2, 7, 5, 3] you should print:

2 3
7 2
5 1
3 0


[Font] [Default] [Show] [Resize] [History] [Profile]