for-loop
What is a for loop in Java?
- 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
}
- 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( updation ): 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.
- It does not return the value by its index number rather than the element.
Key Points:
- 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.
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]