Loops can execute a block of code a number of times. Loops are useful, if you want to run the same code over & over again, each time with a different value.
FOR loops keep running while condition is ‘true’.
A simple example:-
Looping Arrays
The for loop has the following syntax:
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (once) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
Let us consider having an array of birth years & we need to calculate the ages & store them in a new array. The below example will show us how do we get that done using the for loop.
Example:-
Continue & Break Statements
Continue is to exit the current iteration of the loop and continue to the next one.
Example:-
Break is used to completely terminate the whole loop.
Example:-
An Example to exhibit the entire above stated Iteration
Looping Backwards