next up previous
Next: Multidimensional Arrays Up: The Frightened Freshers Guide Previous: While loops

For loops

Well you have seen how a while loop works, now for the better version of it. The for loop. The general way of declaring a for loop is slightly more complex its fine once you have done it a couple of times.


\begin{lstlisting}
for(i=0; i < 5; i++)
{
//do stuff here
}
\end{lstlisting}

Erk. Looks kinda nasty. Its pretty easy really! The first bit, i=0, tells Java that you want to start counting at the number zero. The second bit is just like your boolean condition in the while loop. The last bit is what you want to do every time the first bit of the for loop gets executed. So, using the same example as the while loop, here it is in for loop form.


\begin{lstlisting}
for(i=0; i < 5; i++)
{
car[i] = ''bob'';
}
\end{lstlisting}

There are times that you will want to use a for loop instead of a while loop and vice verca although you probably wont realise until you actually try writing some code and realise that one or the other is neater or does what you want better than the other.


next up previous
Next: Multidimensional Arrays Up: The Frightened Freshers Guide Previous: While loops
Tom Carlson 2006-01-10