Java - For Loop-tutorial
A for loop is a loop that is used to execute the statement a specific number of times.
Syntax:
for (initialization; check_condition; increment / decrement(updation)){//code to be executed}
Components:
- Initialization: It Initializes the value of a variable and is executed only once.
- Check Condition: Here the condition gets checked, if it returns true then the given code is executed, and if false then it comes out of the loop.
- Increment/decrement( update ): It updates the value of the initial variable whether it is increment or decrement.
Example:
package quipoin.java;public class Account {public static void main(String[] args) {// TODO Auto-generated method stubfor (int i=1; i<=5; i++) {}System.out.println(i);}}
Output :
1
2
3
4
5
Nested For Loop:
A nested for loop is a for loop inside another for loop. The inner loop executes completely whenever the outer loop executes.Example:
package quipoin.java;public class NestedForLoop {public static void main(String[] args) {// TODO Auto-generated method stubfor(int i=0;i<n;i++){//inner loopfor(int j=0;j<=i;j++){System.out.print("*");}System.out.println();}}}
Output:
*
**
***
****
*****
For-Each Loop:
For each loop is used on collections classes and arrays.For-Each Loop:
It does not return the value by its index number rather than the element.
Syntax:
for (data_type identifier:Collection Classs){System.out.println(element); //Prints all the elements}
Example:
package quipoin.java;
public class NestedForLoop {
public static void main(String[ ] args) {
int arr[ ]={1,2,3,4,5,6};
//traversing the array with for-each loop
for(int i : arr)
{
System.out.print(i);
}
} }
Output:
123456
Key Point
- This is easy to use as we don't have to increment the value.
- It increases the readability of the code but you can't skip any element and can't print in reverse order using this loop rather than other loops.
Which Loop to Use ?
Loop Type | Use Case |
---|---|
For Loop | When the number of iterations is known |
Nested For Loop | When multiple levels of iteration are needed |
For-Each Loop | When iterating over collections or arrays |