For loop in Java

The for loop in Java is a control flow statement that allows you to repeat a set of statements a specified number of times. It provides a compact way to iterate over a range of values, such as the elements of an array.


The basic syntax of a 'for' loop in Java is as follows:

for (initialization; termination; increment) {
   statement(s);
}

Here's what each part of the for loop does:


  • initialization: This is where you initialize the loop variable. This part of the loop is executed only once at the beginning of the loop.


  • termination: This is the condition that must be met for the loop to continue. If the termination condition is false, the loop will exit.


  • increment: This is where you increment the loop variable. This part of the loop is executed after each iteration of the loop.


  • statement(s): These are the statements that are executed each time the loop runs.


Here's an example that uses a for loop to print the numbers from 1 to 10:

for (int i = 1; i <= 10; i++) {
   System.out.println(i);
}

In this example, i is the loop variable, and it's initialized to 1. The termination condition is

i <= 10
, which means that the loop will run until i is greater than 10. The increment is i++, which increments i by 1 after each iteration of the loop. The System.out.println(i) statement is executed each time the loop runs, printing the value of i.


Here's another example that uses a for loop to find the sum of the first 10 positive integers:

int sum = 0;
for (int i = 1; i <= 10; i++) {
   sum += i;
}
System.out.println("The sum of the first 10 positive integers is: " + sum);

In this example, the sum variable is used to store the sum of the integers, and it's initialized to 0. The loop runs 10 times, adding each integer to the sum variable. After the loop is done, the System.out.println statement outputs the final sum.


In conclusion, the for loop is a powerful and versatile control flow statement that allows you to repeat a set of statements a specified number of times. It's commonly used for tasks such as iterating over arrays and other collections, calculating sums and averages, and generating sequences of numbers.