Learn Java: Loops
Using For Loops

for loops aren’t just a nicer syntax; they also help us remember to increment our counter — something that is easy to forget when we increment with a while loop. Leaving out that line of code would cause an infinite loop — yikes!

Fortunately, equipped with your new understanding of for loops, you can help prevent infinite loops in your own code.



We’ve provided a while loop that loops from 1 to 100 outputting a string on each iteration. Refactor (rewrite) this code as a for loop.

Remember, the syntax of a for loop looks like:

for (int i = 0; i < 5; i++) { // code that will run }
Folder Icon

Take this course for free

Already have an account?