JAVA for loops
JAVA for loops
FOR LOOPS IN JAVA
Okay, for those of you just starting out in java Ive put together some examples of for loops with an explanation on each.
For loops are great for many things but we'll keep it basic for now, they are simply a method of looping a particular task a given number of times. Look at the example below:
JAVA
for (int count=1; count <=5; count++){
system.out.println (count);
}
system.out.println (\"Done\");
================================================== OUTPUT 1 2 3 4 5 Done
So basically, in our header ( (int count=1; count <=5; count++) ) we first have the initialisation (count=1;) this set count's value. We then set the condition to count<=5; , this basically says, as long as counts value is less than or equal to 5, this is then where the increment comes in count++ basically adds 1 to counts current value. So, what the header says is, while counts value is less than or equal to 5, the loop should continue and 1 should be added to counts current value. The loop will stop once count reaches 6 and the code after the for loop will be executed as you can see in the output.
You can have alot of fun with for loops, you can also use a previously declared variable instead of count, for example, if at the start of your program you had the variable int cost=20;, you could then put this into your for loop with cost in place of count. If you get used to using for loops, you will start to see useful ways of using them.
I hope this article has been of some use. Haklite
Arabian 13 years ago
This is a basic FOR loop, not a java loop. The only thing "java' about this is your sysprintln's.
Also, what is the point of making an article about one of the most basic things in programming, and not even providing a comprehensive one?