Results 1 to 3 of 3
  1. #1
    mrjava is offline Member
    Join Date
    Aug 2011
    Posts
    2
    Rep Power
    0

    Default Nested (for) loops in Java

    Hello. I'm new to Java programming and trying hard to learn it :)
    But these nested for loops where is outer and inner for-loop are giving me headache.

    For example this exercise where app asks user the int value and then prints this star pattern. I've been trying to do this but somehow I don't get a hang of it:

    How many rows:
    7

    *
    **
    ***
    ****
    *****
    ******
    ******* (the value is 7 so this prints 7 rows)

    Also different matrix arrays where you are supposed to loop through the array and print values from every element are hard for me.

    Could someone help me at least with that star-pattern exercise and maybe explain what happens in those nested for loops.

    Thank you.

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,023
    Blog Entries
    7
    Rep Power
    20

    Default

    Take those loops apart: here's a small method that prints 'n' stars:

    Java Code:
    public static void stars(int n) {
       for (int i= 0; i < n; i++) // print n stars
          Sytem.out.print('*');
       System.out.println(); // followed by a new line
    }
    Given the small method above, your example can be implemented as follows:

    Java Code:
    for (int j= 1; j <= 7; j++)
       stars(j);
    This code also has a nested loop in it, but the inner loop is implemented in another method. Does this clarify things a bit?

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    mrjava is offline Member
    Join Date
    Aug 2011
    Posts
    2
    Rep Power
    0

    Default

    I found this code from another forum:
    Java Code:
    for(int i=0 ; i<7 ; i++){
      for(int j=0 ; j<i+1 ; j++){
        System.out.print("*");
      }
      System.out.println();
    }
    I almost got it by myself but that inner loops condition j<i+1, what was wrong in my code. Usually it is always the inner loop what I dont get correct. Outer loop is always looping the number of rows, right?

Similar Threads

  1. Replies: 20
    Last Post: 03-22-2011, 04:02 AM
  2. Nested loops
    By Aestuv in forum New To Java
    Replies: 3
    Last Post: 02-10-2011, 11:40 PM
  3. Nested Loops
    By joemama in forum New To Java
    Replies: 1
    Last Post: 01-01-2011, 09:17 PM
  4. Nested for loops
    By luke in forum New To Java
    Replies: 23
    Last Post: 10-21-2010, 02:49 AM
  5. Nested Loops for Java
    By soccer_kid_6 in forum New To Java
    Replies: 4
    Last Post: 02-21-2010, 05:27 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •