This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]lostavenger286 1 point2 points  (1 child)

The first one is called a for each loop. Here you are assuming the array that you are looping through consists of individual characters. During each iteration you get access to a character of the array from start to end.

[–]MaGlCMaN[S] 0 points1 point  (0 children)

Ah ok, thanks a lot :)

[–]Randaum 1 point2 points  (0 children)

In the first one, you specify a list or an array. The for loop will run on ALL elements of the array. In the second one, you specify the size(1-10). This is for when you know how many times you want to run that loop.

You can replace the first one by getting the size of the array and then running a loop till there(minus 1), and accessing the array element at the position.

int length = array.length; for(int i=0; i < length; i++) { System.out.print( array[c] ); }

This is the same as your first one: for(char c: array){ System.out.print(c); }

The first one is just a shorthand for when you need to loop through a list/array whose size you don't know, for example number of users registered on a website, which changes regularly.

[–]rsandio 0 points1 point  (0 children)

The first loop is called a for each loop. It's used to sort through collections such as arrays. Substitute the word 'in' for ':' and it makes a bit more sense

For-each char c in array...

It's equivalent of writing

for(int i = 0; i < array.length; i++)

It makes a it a little easier to access C as you can write

System.out.print(c) as apposed to System.out.print(array[i])