In Java, the for
loop is a control flow statement that is used to execute a block of code repeatedly for a fixed number of times. The for
loop has the following syntax:
for (initialization; condition; update) { // code to be executed repeatedly }
The initialization
expression is executed only once at the beginning of the loop and is used to initialize the loop variable. The condition
expression is checked before each iteration of the loop and is used to determine whether the loop should continue or terminate. The update
expression is executed after each iteration of the loop and is used to update the loop variable.
Here is an example of how to use 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, the initialization
expression initializes the loop variable i
to 1, the condition
expression checks whether i
is less than or equal to 10, and the update
expression increments i
by 1 after each iteration of the loop. The output will be:
1 2 3 4 5 6 7 8 9 10
Here is another example of how to use a for
loop to calculate the sum of the first 10 integers:
int sum = 0; for (int i = 1; i <= 10; i++) { sum += i; } System.out.println("The sum of the first 10 integers is " + sum);
In this example, the initialization
expression initializes the loop variable i
to 1, the condition
expression checks whether i
is less than or equal to 10, and the update
expression increments i
by 1 after each iteration of the loop. Inside the loop, the sum
variable is updated by adding the value of i
to it. The output will be:
The sum of the first 10 integers is 55
Nested Loops
In Java, a nested loop is a loop inside another loop. It allows you to iterate over a set of data in a more complex pattern than a single loop could achieve.
The general syntax of a nested loop is as follows:
for (initialization; condition; update) { // code to be executed repeatedly for (inner_initialization; inner_condition; inner_update) { // code to be executed repeatedly } }
Let’s consider the following example of a nested loop that prints out a multiplication table for numbers 1 to 10:
for(int i=1; i<=10; i++) { for(int j=1; j<=10; j++) { System.out.print(i*j + "\t"); } System.out.println(); }
In this code, we have an outer loop that iterates through the numbers 1 to 10, and an inner loop that also iterates through the numbers 1 to 10. The inner loop multiplies the current value of i
by j
and prints the result. After each inner loop is completed, we print a new line to start a new row of the multiplication table.
The output of this code will look like:
As you can see, the nested loop allowed us to iterate through all possible combinations of i
and j
, and generate a table of multiplication results.