Imagine a situation where you have to print something a hundred times. How would you do that?
You could type the command a hundred times, or maybe copy-paste it repeatedly – but you probably wouldn’t want to.
This is where loops come into use. When using a for-loop, those hundred lines of code can be written in as few as three to four statements.
A for-loop allows a particular set of statements, written inside the loop, to be executed repeatedly until a specified condition is satisfied.
This code will print out the first ten natural numbers using a for-loop in Java.
class Sample{public static void main(String args[]) {int start = 1; // starting conditionint end = 10; // ending conditionfor (int index = start; index <= end; index++) {System.out.println("Value of index: "+ index);}}}
The loop will run ten times, printing the first ten natural numbers, until the terminating condition is met, i.e., when the index is equal to ten.
Free Resources