For loop in Java is used to iterate a part of the program n number of times. There are other types of loops like while loop or do-while loop but they are used when the number of iteration is not known in advance and for loop is used when the number of iteration is fixed or known in advance.
A simple for loop consists of three parts:
- Initialization: It is the initial condition of a loop that executes only once before the execution of the code block.
- Condition: The loop will keep executing until the condition become false. This condition is tested each time before each iteration.
- Increment/Decrement: It executes every time after the block of code gets executed.
Example: Write a Java Program to Print all natural numbers from 1 to 10. (Simple loop)
public class Main
{
public static void main(String[] args) {
for(int i = 1; i <= 10; i++){
System.out.println(i);
}
}
}
Output:
1 2 3 4 5 6 7 8 9 10
Example: Write a Java Program to Print 3X3 matrix (nested loop).
public class Main
{
public static void main(String[] args) {
for(int i = 0; i < 3; i++){
System.out.print(i);
for(int j = 0; j < 3; j++){
System.out.print(" "+j);
}
System.out.println("\n");
}
}
}
Output:
0 0 1 2 1 0 1 2 2 0 1 2
Example: Write a Java Program to Print all the elements of an Array. (for each loop)
Here, we are using a for-each loop to traverse all the elements of an array. For-each loop syntax is different from simple for loop.
//syntax of for-each loop for(type var : arr) { //statement; }
public class Main
{
public static void main(String[] args) {
int[] arr = {10, 15, 20, 25, 30, 35, 40};
for(int i : arr) {
System.out.print(i+" ");
}
}
}
Output:
10 15 20 25 30 35 40
No comments:
Post a Comment