Types of nested loops in Java

I have a simple question. I need to find as many nested loops as possible in java. I have something like a loop and if the statement is inside. I know we can do something like this. just need to know a little more about the more types of nested loops.

if you can write some examples. I'll be very happy. thanks.

public class Test {
    public static void main (String []args) {
        int i = 0;

        for(int j = 1; j <= 5; j++) {
            if(j == 1 || j == 5) {
                i = 4;
            } else {
                i = 1;
            }
            for(int x = 0; x < i; x++) {
                System.out.print("**");
            }
            System.out.println();
         }
    }
}

      

+2


a source to share


6 answers


You can nest as many for

/ loops while

as you need in Java: there is no practical limit.

There are 4 loops in Java:

Java does not goto

(which is not really required).

see also


Examples of

This is a typical example of a simple "triangle" type of nested loop, where the number of iterations of the inner loop depends on the value that is repeated in the outer loop:

for (int i = 1; i <= 5; i++) {     // prints:
   for (int j = 0; j < i; j++) {   // *
      System.out.print("*");       // **
   }                               // ***
   System.out.println();           // ****
}                                  // *****

      

Here's an example of a nested pairing loop in which two loops are independent of each other using the for-each construct:

int[] numbers = { 1, 2, 3 };                       // prints:  // if swapped:
char[] letters = { 'A', 'B', 'C' };                // 1 A      // 1 A
                                                   // 1 B      // 2 A
for (int number : numbers) {                       // 1 C      // 3 A
   for (char letter : letters) {                   // 2 A      // 1 B
       System.out.println(number + " " + letter);  // 2 B      // 2 B
   }                                               // 2 C      // 3 B
}                                                  // 3 A      // 1 C
                                                   // 3 B      // 2 C
                                                   // 3 C      // 3 C

      

The construct for-each

, which has no explicit indices, makes the independence of both loops obvious: you can swap two operators for

in the above code, and you still get all the pairs, although they are listed in a different order.

This method use boolean

for a loop while

(this one java.util.Scanner

) is typical:

Scanner sc = new Scanner("here we go again");     // prints:
while (sc.hasNext()) {                            // hereeeee
   String s = sc.next();                          // weeeee
   char lastChar = s.charAt(s.length() - 1);      // gooooo
   for (int i = 0; i < 4; i++) {                  // againnnnn
      s += lastChar;
   }
   System.out.println(s);
}

      



And here's an example showing how do-while

different from while-do

and for

:

    int x = 0;
    do {
        System.out.println("Hello!!!");
    } while (x != 0);

      

The above loop prints Hello!!!

: the body do-while

is executed before the termination condition is checked.


More complex example

Here's an example of nested loop logic, but refactored into methods to make things more readable. This is what is important for beginners to learn: just because you can physically set the loops in as many levels as you want doesn't mean you should . By breaking down the logic in this way, the program becomes more modular and readable, and each logic stands on its own and can be tested and reused, etc.

This snippet reverses the letters of the word in char[]

in place.

static void swap(char[] arr, int i, int j) {
    char t = arr[i];
    arr[i] = arr[j];
    arr[j] = t;
}
static void reverse(char[] arr, int from, int to) {
    int N = (to - from);
    for (int i = 0; i < N / 2; i++) {
        swap(arr, from+i, to-1-i);
    }
}
public static void main(String[] args) {
    char[] sentence = "reversing letters of words in sentence".toCharArray();
    final int L = sentence.length;
    int last = 0;
    for (int i = 0; i <= L; i++) {
        if ((i == L) || (sentence[i] == ' ')) {
            reverse(sentence, last, i);
            last = i + 1;
        }
    }
    System.out.println(new String(sentence));
    // prints "gnisrever srettel fo sdrow ni ecnetnes"
}

      

This example is also instructive in that while it is essentially a nested loop algorithm, it is actually O(N)

! It is a mistake to think that any double nested loop algorithm should be O(N^2)

- it really depends on the algorithm itself more than on the physical structure.


Nested Loop Algorithms

These are classic algorithms traditionally implemented using nested loops (at least in naive forms):

  • O(N^2)

    Sorting algorithms:
  • O(N^3)

    three times nested loop algorithms:
  • Algorithms for dynamic programming of table filling
    • Levenshtein distance ( O(N^2)

      , row edit distance)
    • Floyd-Warshall Algorithm ( O(N^3)

      , shortest path of all pairs in a graph)

This is far from an exhaustive selection, but it should provide a good introduction to various nested looping algorithms for

for beginners.

+6


a source


This code is if { if { if { ... } } }

not an example of nested loops. if

does not use a loop.



Loop expressions are, for example, for

and while

.

+1


a source


The cycles may be performed using three basic operators cycle for

, while

and do..while

. However, if your question is about how many types of nested loops are possible in Java, I would say LOTS, since you can order and mix them as you see fit.

+1


a source


I like the previous answer, but in an attempt to answer this curious question directly:

if-else

is not a loop type. Java has loops for

, while

and do-while

. You can argue that the foreach syntax for loops for

introduced in Java 5 is a different type of loop for your purpose. But it's actually just shorthand for writing a while loop.

But all these "different" types of loops are just language constructs. In the byte code that is compiled, they do not differ from each other.

+1


a source


I guess it depends on the compiler. I wrote a simple test program that generates Java files with different levels of loop nesting.

import java.io.BufferedWriter;
import java.io.FileWriter;

public class NestingTest
{
    public static void main(String[] args) throws Exception
    {
        for (int n = 1; n < 10000; ++n)
        {
            String className = "test" + n;
            FileWriter fw = new FileWriter("f:/test/" + className + ".java");
            BufferedWriter o = new BufferedWriter(fw);
            o.write("public class ");
            o.write(className);
            o.write("\n{\npublic static void main(String[] args) {\n");
            for (int i = 0; i < n; ++i)
            {
                o.write("while(true) {\n");
            }
            for (int i = 0; i < n; ++i)
            {
                o.write("}\n");
            }
            o.write("}\n}\n");
            o.close();
        }
    }
}

      

Once the files are generated, you do a manual binary search. Compile test5000. If it succeeds, compile test7500, if not, compile test2500. After 13 or 14 steps, you should come to a conclusion.

My sweetspot compiler seems to be 5345 nesting levels for this simple program, so I guess in practice it doesn't matter at all.

+1


a source


Yes, nesting has no limit.

0


a source







All Articles