For loop in java

For loop is a control flow statement in Java that is used to iterate over a range of values. It repeatedly executes a set of statements for a specified number of times. For loops in Java are used to perform a task multiple times with a specific increment or decrement. The basic syntax of a for loop in Java is as follows:

for (initialization; condition; increment/decrement) {
   statement(s);
}

The initialization part of the for loop is used to initialize the loop variable. The condition is a boolean expression that is evaluated before each iteration of the loop. If the condition is true, the loop will continue to execute; otherwise, it will exit the loop. The increment/decrement part of the for loop is used to update the value of the loop variable after each iteration.

For example, the following for loop will print the numbers from 1 to 10:

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

The for loop can also be used to iterate over arrays or collections in Java. For example, the following for loop can be used to print all the elements of an array:

int[] numbers = {1, 2, 3, 4, 5};
for (int i=0; i<numbers.length; i++) {
   System.out.println(numbers[i]);
}

For loops can also be nested, i.e., one for loop can be inside another for loop. In such a case, the inner loop will be executed completely for each iteration of the outer loop. For example, the following code will print all the multiplication tables from 1 to 10:


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

In conclusion, for loops in Java are a powerful tool for repeating a set of statements for a specified number of times. They can be used to iterate over arrays, collections, or perform complex calculations. Understanding how for loops work and when to use them is an important aspect of programming in Java.

Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in