for-loop
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 quipohouse;
public class ForLoop {
public static void main(String[] args) {
for (int i=1; i<=; 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 quipohouse;
public class NestedForLoop {
public static void main(String[] args) {
//outer loop
for(int i=0;i<n;i++)
{
//inner loop
for(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 quipohouse;
class ForEachLoop {
public static void main(String args[]){
//declaring an array
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 |