for Loop
for Loop
Loops in any programming language are used to execute a block of code again and again until a base condition is achieved. As soon as a base condition is satisfied the loop is terminated and the control is returned to the main body of the program.
There are three types of loops in java:
- for loop
- while loop
- do……while loop
for loop:
Whenever a loop needs to be run a specific number of times, we use a for loop.
Syntax:
- initializeVariable: initialize a new variable or use an already existing one.
- testCondition: It checks the testing condition of the loop after each iteration and returns a Boolean value, which determines if the loop should be terminated or not.
- Increment/decrement: It is used to increment or decrement the variable after each iteraton.
Example:
Output:
We also have a special syntax for iterating through arrays and other collection objects, also called as a for-each loop.
Syntax:
Example:
Output:
And lastly we have an infinite for loop, wherein the expression always evaluates to true, hence running indefinitely.
Example:
Output:
The loop will keep on running until you halt the program.