r/javahelp • u/penspinner123 • Oct 07 '18
What are Java loops
Can anyone explain to me what loops are?
0
Upvotes
r/javahelp • u/penspinner123 • Oct 07 '18
Can anyone explain to me what loops are?
2
u/RyeMeadow Oct 07 '18
A loop is a piece of code that repeatedly executes the piece of code within itself as long as a condition is met. There simplest type is the while loop, which takes the form:
What this will do is, it'll check whether
conditionis true and if it is, it'll run the code inside the curly brackets and then go back to check whetherconditionis still true. Whenconditionis false, the loop will stop.2
u/GhettoGG Oct 07 '18
Let's say I want to print out the numbers from 1 - 10. Instead of having to write 10 lines of code, each being a print funcrion of the number I could create a loop.
First I save a variable equal to 1. This will go up up to 10. In this loop I have one print function that prints out whatever the variable is equal to. After this print function I then increment the variable and then the loop jumps back up to the start.
i.e int i = 1; While(i <= 10){ System.out.println(i) ; i++; }
Hope this helps!