tags:

views:

461

answers:

6

Hi guys. I have a simple question. I have to find out many nested loops as possible in java. I have something like for loop and if statement inside. i know that we can do like if{if{if{if{ something like that too. just need some more idea of more types of nested loops.

if you can write down some examples. I'll be very glad. thank you.

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: 

You can nest as many for/while loops as you'd practically want in Java: there's no practical limit.

Java has 4 looping constructs:

Java does not have goto (which isn't really needed anyway).

See also


Examples

This is a typical example of a simple "triangle"-type nested loop, where the number of iteration of the inner loop depends on the value being iterated 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 "pairing"-type nested loop, where the 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 for-each construct, which lacks explicit indices, makes the indepedence of both loops obvious: you can swap the two for statements in the above code, and you'd still get all pairs, though listed in a different order.

This use of a boolean method for a while loop (this one from 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 that shows how do-while is different from while-do and for:

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

The above loop prints Hello!!!: the body of a do-while is executed before the termination condition is checked.


A more elaborate example

Here's an example of a nested-loop logic, but refactored into methods to make things more readable. This is something that is important for beginners to learn: just because you can physically nest loops as many levels as you want, doesn't mean you should. By breaking apart the logic like this, 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 a word in a 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 even though it's essentially a nested loop algorithm, it's actually O(N)! It's a mistake to think that any doubly nested-loop algorithm must be O(N^2) -- it really depends on the algorithm itself more than just the physical structure.


Nested-loop Algorithms

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

These are far from an exhaustive sampling, but it should provide a good introduction to a variety of nested for loops algorithms for beginners.

polygenelubricants
thank you very much. the reason I am asking you this was I have to group book project about nested loop. I wanted to show many many types of nested loops as possible. so, while, for, if are the only things we can use??
dominoos
@dominoos: are you asking how many control structures there are in Java? Because that's an entirely different question.
polygenelubricants
I was asking for examples of nested loops. and I wanted to show verities of nested loops.
dominoos
@dominoos: I can't be doing your group book project for you. I've done all I can here, sorry.
polygenelubricants
+1  A: 

The code if { if { if { ... } } } is not an example of nested loops. if does not use loop.

Looping expressions are for example for and while.

Mark Byers
+1  A: 

Yeah, nesting has no limit.

fastcodejava
Actually, there is a theoretical limit in that a single class can only have 64K bytes of bytecodes. But in practice, you are unlikely to reach that limit by simply nesting loops.
Stephen C
+1  A: 

Loops can be done using the 3 basic loop statements: for, while and do..while. However, if your question is about how many types of nested loops are possible in Java, I'd say LOTS, since you can arrange and mix them as you wish.

jweyrich
A: 

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

if-else is not a loop type. Java has for, while, and do-while loops. You could argue the the "foreach" syntax for for loops, introduced in Java 5, is a different kind of loop for your purpose. But really it is just shorthand for writing a while loop.

But all of these "different" loop types are just language constructs. In the byte code that is compiled, they're not intrinsically different.

Sean Owen
+1  A: 

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, and if it doesn't, compile test2500. After 13 or 14 steps, you should come to a conclusion.

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

FredOverflow