0% found this document useful (0 votes)
16 views10 pages

Types of Loops in Java

The document provides an overview of loops in Java, detailing the types of for loops including simple, for-each, and labeled loops. It explains the syntax and structure of each loop type, along with examples and outputs. Additionally, it compares the for loop with while and do-while loops, highlighting when to use each type based on iteration needs.

Uploaded by

abhay9955yadav
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views10 pages

Types of Loops in Java

The document provides an overview of loops in Java, detailing the types of for loops including simple, for-each, and labeled loops. It explains the syntax and structure of each loop type, along with examples and outputs. Additionally, it compares the for loop with while and do-while loops, highlighting when to use each type based on iteration needs.

Uploaded by

abhay9955yadav
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Loops in Java

The Java for loop is used to iterate a part of the program several times. If the number
of iteration is fixed, it is recommended to use for loop.

There are three types of for loops in Java.

o Simple for Loop


o For-each or Enhanced for Loop
o Labeled for Loop

Java Simple for Loop


A simple for loop is the same as C/C++. We can initialize the variable, check condition
and increment/decrement value. It consists of four parts:

1. Initialization: It is the initial condition which is executed once when the loop starts.
Here, we can initialize the variable, or we can use an already initialized variable. It is an
optional condition.
2. Condition: It is the second condition which is executed each time to test the condition
of the loop. It continues execution until the condition is false. It must return boolean
value either true or false. It is an optional condition.
3. Increment/Decrement: It increments or decrements the variable value. It is an
optional condition.
4. Statement: The statement of the loop is executed each time until the second condition
is false.

Syntax:

6.2M

108

Hello Java Program for Beginners

1. for(initialization; condition; increment/decrement){


2. //statement or code to be executed
3. }

Flowchart:
Example:

[Link]

1. //Java Program to demonstrate the example of for loop


2. //which prints table of 1
3. public class ForExample {
4. public static void main(String[] args) {
5. //Code of Java for loop
6. for(int i=1;i<=10;i++){
7. [Link](i);
8. }
9. }
10. }
Test it Now
Output:

1
2
3
4
5
6
7
8
9
10

Java Nested for Loop


If we have a for loop inside the another loop, it is known as nested for loop. The inner
loop executes completely whenever outer loop executes.

Example:

[Link]

1. public class NestedForExample {


2. public static void main(String[] args) {
3. //loop of i
4. for(int i=1;i<=3;i++){
5. //loop of j
6. for(int j=1;j<=3;j++){
7. [Link](i+" "+j);
8. }//end of i
9. }//end of j
10. }
11. }

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Pyramid Example 1:
[Link]

1. public class PyramidExample {


2. public static void main(String[] args) {
3. for(int i=1;i<=5;i++){
4. for(int j=1;j<=i;j++){
5. [Link]("* ");
6. }
7. [Link]();//new line
8. }
9. }
10. }

Output:

*
* *
* * *
* * * *
* * * * *

Pyramid Example 2:

[Link]

1. public class PyramidExample2 {


2. public static void main(String[] args) {
3. int term=6;
4. for(int i=1;i<=term;i++){
5. for(int j=term;j>=i;j--){
6. [Link]("* ");
7. }
8. [Link]();//new line
9. }
10. }
11. }

Output:

* * * * * *
* * * * *
* * * *
* * *
* *
*

Java for-each Loop


The for-each loop is used to traverse array or collection in Java. It is easier to use than
simple for loop because we don't need to increment value and use subscript notation.

It works on the basis of elements and not the index. It returns element one by one in
the defined variable.

Syntax:

1. for(data_type variable : array_name){


2. //code to be executed
3. }

Example:

[Link]

1. //Java For-each loop example which prints the


2. //elements of the array
3. public class ForEachExample {
4. public static void main(String[] args) {
5. //Declaring an array
6. int arr[]={12,23,44,56,78};
7. //Printing array using for-each loop
8. for(int i:arr){
9. [Link](i);
10. }
11. }
12. }
Test it Now

Output:

12
23
44
56
78
Java Labeled For Loop
We can have a name of each Java for loop. To do so, we use label before the for loop.
It is useful while using the nested for loop as we can break/continue specific for loop.

Note: The break and continue keywords breaks or continues the innermost for loop
respectively.

Syntax:

1. labelname:
2. for(initialization; condition; increment/decrement){
3. //code to be executed
4. }

Example:

[Link]

1. //A Java program to demonstrate the use of labeled for loop


2. public class LabeledForExample {
3. public static void main(String[] args) {
4. //Using Label for outer and for loop
5. aa:
6. for(int i=1;i<=3;i++){
7. bb:
8. for(int j=1;j<=3;j++){
9. if(i==2&&j==2){
10. break aa;
11. }
12. [Link](i+" "+j);
13. }
14. }
15. }
16. }

Output:

1 1
1 2
1 3
2 1
If you use break bb;, it will break inner loop only which is the default behaviour of any
loop.

[Link]

1. public class LabeledForExample2 {


2. public static void main(String[] args) {
3. aa:
4. for(int i=1;i<=3;i++){
5. bb:
6. for(int j=1;j<=3;j++){
7. if(i==2&&j==2){
8. break bb;
9. }
10. [Link](i+" "+j);
11. }
12. }
13. }
14. }

Output:

1 1
1 2
1 3
2 1
3 1
3 2
3 3

Java Infinitive for Loop


If you use two semicolons ;; in the for loop, it will be infinitive for loop.

Syntax:

1. for(;;){
2. //code to be executed
3. }

Example:

[Link]
1. //Java program to demonstrate the use of infinite for loop
2. //which prints an statement
3. public class ForExample {
4. public static void main(String[] args) {
5. //Using no condition in for loop
6. for(;;){
7. [Link]("infinitive loop");
8. }
9. }
10. }

Output:

infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
ctrl+c

Now, you need to press ctrl+c to exit from the program.

Java for Loop vs while Loop vs do-while Loop

Comparison for loop while loop do-while loop

Introduction The Java for loop is a control The Java while loop is a The Java do while loop is a
flow statement that iterates a control flow statement control flow statement that
part of the programs multiple that executes a part of executes a part of the
times. the programs repeatedly programs at least once and
on the basis of given the further execution
boolean condition. depends upon the given
boolean condition.

When to use If the number of iteration is If the number of iteration If the number of iteration is
fixed, it is recommended to is not fixed, it is not fixed and you must
use for loop. recommended to use have to execute the loop at
while loop. least once, it is
recommended to use the
do-while loop.
Syntax for(init;condition;incr/decr){ while(condition){ do{
// code to be executed //code to be executed //code to be executed
} } }while(condition);

Example //for loop //while loop //do-while loop


for(int i=1;i<=10;i++){ int i=1; int i=1;
[Link](i); while(i<=10){ do{
} [Link](i); [Link](i);
i++; i++;
} }while(i<=10);

Syntax for for(;;){ while(true){ do{


infinitive loop //code to be executed //code to be executed //code to be executed
} } }while(true);

Common questions

Powered by AI

The for-each loop in Java does not support operations such as accessing the current iteration index or modifying the data structure being iterated over directly, which are possible with traditional for loops. It is primarily read-only with respect to modifying elements in place. While suitable for reading data or when direct index manipulation isn't needed, it is not ideal when modification of the underlying structure is required, such as removing elements or modifying items by index .

The simple for loop, for-each loop, and labeled for loop in Java have distinct structures and use cases. The simple for loop is used for iteration where the number of iterations is fixed, consisting of initialization, condition, and increment/decrement. The for-each loop is simpler as it iterates over arrays or collections directly, without using index variables, and is best when you need to access elements one by one. The labeled for loop allows labels for loops to specify which loop to break or continue in nested scenarios, useful for controlling complex iteration flows by breaking out of multiple loops .

A labeled break statement is particularly useful in Java when there's a need to exit several nested loops simultaneously upon satisfaction of a condition. This reduces complexity by avoiding multiple flag checks or redundant conditions to ensure correct loop exits. It is most beneficial in algorithms requiring early exits to optimize performance or simplify logic when an exit condition isn't straightforward to achieve with a single loop break .

Java loops can be effectively illustrated with simple, clear examples that gradually increase in complexity. Starting with a simple for loop counting from 1 to 10 helps beginners understand the basic syntax and flow. Nested loops can be introduced with visual outputs, like printing a number matrix, demonstrating iteration within iteration. Examples like PyramidExample.java show how nested structures can construct familiar patterns, reinforcing understanding of loops' role in shaping outputs .

Infinite loops in Java occur when a loop has no terminating condition or is impossible to meet, often written as for(;;) or while(true). These can cause programs to hang and consume resources indefinitely, potentially freezing the system. They are mitigated by ensuring exit conditions are present and reachable within the loop, or by using a break statement when an external condition prompts termination .

Nested for loops can construct data structures like pyramids by controlling the number of elements printed per line. The outer loop determines the number of rows, and the inner loop controls elements per row, often limited by the current row number. In PyramidExample.java, the outer loop iterates for each row, and the inner loop prints '*' characters increasing per row. This double loop structure facilitates constructing incrementally structured outputs like pyramids .

The for-each loop is generally more readable and concise than the simple for loop when iterating over arrays or collections, as it eliminates the need for managing index variables. This reduces potential errors related to incorrect index handling. However, while it simplifies code, it can be less efficient in scenarios requiring index manipulation or when an operation requires knowing element positions. Thus, for-each is preferred for straightforward iteration, while simple for loops are better for index-based operations .

The do-while loop executes the loop body at least once because it evaluates the condition after executing the statements, which differs from for and while loops that check conditions beforehand. It is suited for scenarios where initial execution of the loop block is mandatory before any condition checks, like menu options or retries prompts, ensuring statements execute regardless of initial condition truth .

The Java for loop is preferred when the number of iterations is known and fixed, allowing explicit initialization, condition check, and increment/decrement in one line. The while loop is better suited when the number of iterations is unknown, as its continuation depends on a boolean condition evaluated before executing the loop body. Thus, for loop is generally used for counting iterations, whereas while is used for more complex conditional iteration .

Labeled for loops in Java allow specifying which loop to break or continue in nested structures, improving control flow by breaking out of multiple loops with a single statement. This provides clarity in complex scenarios where standard break or continue statements only affect the innermost loop. However, excessive usage can reduce code readability and obscure the logical flow, risking maintenance difficulties .

You might also like