For Loop in Java Best Example | Java for loop With Example

For Loop in Java Best Example : – here’s an example of a for loop in Java:

Example 1

public class A   {
public static void main(String[] args) {
	for(int i=0; i<5; i++) {
		System.out.println("Hello");
	}
}
}
Output : 
Hello
Hello
Hello
Hello
Hello

Note : – Use Break Keyword in Java for loop

  • It Should be Used Only inside Loops or Switch.
  • It Will Exit Loop.

Example 2

public class A   {
public static void main(String[] args) {
	for(int i=0; i<5; i++) {
		System.out.println(50);
		break;
	}
}
}
Output : 50

You Also Learn –

For Loop in Java Best Example

Example 3: The following program prints the sum of x ranging from 1 to 20.  

public class A   {
public static void main(String[] args) {
	int sum = 0;
	for (int x=1; x<= 20; x++) {
		 sum = sum + x;
	
	}
	System.out.println(sum);
}
}
Output : 210
for (int i = 0; i < 10; i++) {
    System.out.println("Iteration " + i);
}

In this example, the for loop starts with an initialization statement int i = 0, which sets the loop counter variable i to 0.

The loop condition i < 10 is then checked, and if it is true, the loop body is executed. In this case, the loop body simply prints the current iteration number using System.out.println().

After the loop body is executed, the update statement i++ is executed, which increments the loop counter variable i by 1. The loop then repeats, checking the loop condition again and executing the loop body as long as the condition is true.

This particular for loop will execute 10 times, since the loop condition i < 10 will be true for i values from 0 to 9. The output of this for loop would be:

Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Iteration 6
Iteration 7
Iteration 8
Iteration 9

Leave a Comment