Page 1 of 2 12 LastLast
Results 1 to 20 of 24
  1. #1
    luke is offline Member
    Join Date
    Sep 2010
    Posts
    62
    Rep Power
    0

    Question Nested for loops

    Hi,
    I have to display a diamond shape using asterisks. At the beginning I start with four ' ' (single space) followed by one '*' and again four ' ' symbol. The second line is four minus one ' ' followed by one plus two '*' and again four minus one ' ' and so on.

    Java Code:
    static void printDiamond() {
            
            for( int i = 1; i <= 4; i++ )
                System.out.print(' ');
            
            System.out.print('*');
            
            for( int i = 1; i <= 4; i++ )
                System.out.print(' ');
                
            System.out.println();
            
            for( int i = 1; i <= 3; i++ )
                System.out.print(' ');
            
            for( int i = 1; i <= 3; i++ )
                System.out.print('*');
            
            for( int i = 1; i <= 3; i++ )
                System.out.print(' ');
            
            System.out.println();
            
            for( int i = 1; i <= 2; i++ )
                System.out.print(' ');
            
            for( int i = 1; i <= 5; i++ )
                System.out.print('*');
            
            for( int i = 1; i <= 2; i++ )
                System.out.print(' ');
    
    and so on (I am not pasting the whole code since it is going to be too much lines)
            
        }

    I tried to do this by using nested for loops but I couldn't make the diamond shape. That's why I am using for loops one after another.
    The idea is that I want to use more for loops and less output statements.
    Any hints are more than welcome.

  2. #2
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default

    I would sketch how this would look on paper first, including println logic

  3. #3
    luke is offline Member
    Join Date
    Sep 2010
    Posts
    62
    Rep Power
    0

    Default

    Quote Originally Posted by al_Marshy_1981 View Post
    I would sketch how this would look on paper first, including println logic
    I already did it.

  4. #4
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default

    looks like the thickest part of the diamond is nine char's long and the height is 9 chars long. that should be a big clue
    assume chars are * .

    ****'*'****

    centre in any row is always the 5th char '*' and char length is always 9

    I bet you can get it from here...

  5. #5
    luke is offline Member
    Join Date
    Sep 2010
    Posts
    62
    Rep Power
    0

    Default

    Quote Originally Posted by al_Marshy_1981 View Post

    I bet you can get it from here...
    Unfortunately I can't. May be some more hints...
    Just to clarify - for this task I am supposed to use nested for loops and as less as possible System.out.print

  6. #6
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default

    I am actually having a go at it myself as we speak, good challenge! I misread your post originally, sorry, will post any findings.

  7. #7
    luke is offline Member
    Join Date
    Sep 2010
    Posts
    62
    Rep Power
    0

    Default

    Quote Originally Posted by al_Marshy_1981 View Post
    I am actually having a go at it myself as we speak, good challenge! I misread your post originally, sorry, will post any findings.
    If it is done with for loops one after another it's easy. But with nested for loops, as less as possible System.out.prints and nothing else more then it gets interesting (well, at least to me).
    Thanks for your replies btw, al_Marshy_1981.
    Last edited by luke; 10-16-2010 at 04:52 AM.

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by luke View Post
    If it is done with for loops one after another it's easy. But with nested for loops, as less as possible System.out.prints and nothing else more then it gets interesting (well, at least to me).
    Thanks for your replies btw, al_Marshy_1981.
    Hm, let's see your attempt with nested loops to see just what you're doing wrong.

  9. #9
    luke is offline Member
    Join Date
    Sep 2010
    Posts
    62
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    Hm, let's see your attempt with nested loops to see just what you're doing wrong.

    Java Code:
    static void printDiamond() {
            
            for( int i = 4; i >= 0; i-- ) {
                System.out.print(' ');
                
                for( int j = 1; j <= 9; j += 2 ) {
                    System.out.print('*');
                    
                    for( int k = 4; k >= 0; k--) {
                        System.out.print(' ');
                        
                    }
                    
                }
            }
        }
    This is the last version of what I was playing with. I don't keep the previous attempts since they were not working correctly either.
    Thanks, Fubarable.

    I recall one of the previous attempts:

    Java Code:
    for( int i = 4; i >= 0; i-- ) {
                            
                for( int j = 1; j <= 9; j += 2 ) {
                          
                    for( int k = 4; k >= 0; k--) {
                        System.out.print(' ');
                        System.out.print('*');
                        System.out.print(' ');
                        System.out.println();
    }
    }
    }
    but it was making no sense,as well.
    Last edited by luke; 10-16-2010 at 05:19 AM.

  10. #10
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default

    I have got it down to 4 prints, just ironing out an array index bug I cant find, I got the diamond printing

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Use Math.abs and you can get it down to just two System.out.prints and one System.out.println. No need for arrays, just some basic math.

  12. #12
    luke is offline Member
    Join Date
    Sep 2010
    Posts
    62
    Rep Power
    0

    Default

    Quote Originally Posted by al_Marshy_1981 View Post
    I have got it down to 4 prints, just ironing out an array index bug I cant find, I got the diamond printing
    I am not supposed to use arrays.

  13. #13
    luke is offline Member
    Join Date
    Sep 2010
    Posts
    62
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    Use Math.abs and you can get it down to just two System.out.prints and one System.out.println. No need for arrays, just some basic math.
    Hm,interesting. I'll need to think about it.

  14. #14
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Hint: The key is to count the left spaces and the stars and try to figure out formulas:

    Java Code:
    i		spaces		stars
    =====================================
    0		4		1
    1		3		3
    2		2		5
    3		1		7
    4		0		9
    5		1		7
    6		2		5
    7		3		3
    8		4		1
    You will have one outer loop going from int i = 0 to i < 9 and nested in the outer loop are 2 inner loops, one after the other. The first for the spaces the second for the stars, followed by a println.
    Last edited by Fubarable; 10-16-2010 at 06:04 AM.

  15. #15
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default

    Quote Originally Posted by luke View Post
    I am not supposed to use arrays.
    Awww darn it! just got it working, going to try that Math.abs now :D

  16. #16
    luke is offline Member
    Join Date
    Sep 2010
    Posts
    62
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    Hint: The key is to count the left spaces and the stars and try to figure out formulas:

    Java Code:
    i		spaces		stars
    =====================================
    0		4		1
    1		3		3
    2		2		5
    3		1		7
    4		0		9
    5		1		7
    6		2		5
    7		3		3
    8		4		1
    You will have one outer loop going from int i = 0 to i < 9 and nested in the outer loop are 2 inner loops, one after the other. The first for the spaces the second for the stars, followed by a println.

    Fubarable, thanks a lot for your hints. I've been working on this for a couple of hours. I've made some progress but it's not enough. This is what I've got so far:

    Java Code:
    static void printDiamond() {
            
            for( int i = 0; i < 9; i++ ){
                
                for( int j = Math.abs(i - 4); j > 0; j -= 1)
                    System.out.print(' ');
                
                for( int k = 2 * i + 1; k >= i; k-- ){
                    System.out.print('*');
                }
                System.out.println();
                    
                }
                
            }


    but the result is
    If you can possibly give me some more hints because I am stuck...

  17. #17
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    You're close.

    If you look at my "hint" table again, you'll see a relationship between spaces and stars --
    namely: (2 * spaces) + stars = what?

    So, inside your outer for loop, just before your inner for loop, calculate spaceMax and use it in the for loop, then use this number and MAX (9) to calculate starMax:

    Java Code:
    public class Fu2 {
       private static final int MAX = 9;
    
       public static void main(String[] args) {
          for (int i = 0; i < MAX; i++) {
             int spaceMax = Math.abs(MAX/2 - i);
             for (int j = 0; j < spaceMax; j++) {
                System.out.print(" ");
             }
             
             int starMax = // [color="red"]*** use MAX and spaceMax to calculate this ***[/color]
             for (int j = 0; j < starMax; j++) {
                System.out.print("*");
             }
             System.out.println("");
          }
       }
    }

    Having said all this, you really don't need to use Math.abs, but instead could do all this with a simple if condition, but I think the Math.abs is cooler, and makes it easier to be able to create a diamond of any size.

    Luck!

  18. #18
    luke is offline Member
    Join Date
    Sep 2010
    Posts
    62
    Rep Power
    0

    Default

    Thanks again for your help, Fubarable. Without your assistance I wouldn't be able to do it.
    When I started this problem I thought it's easy. But eventually turned out to be challenging (at least to me).
    The solution with Math.abs is very cool. Nice, short and flexible code :) Thank you.

  19. #19
    luke is offline Member
    Join Date
    Sep 2010
    Posts
    62
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    You're close.

    If you look at my "hint" table again, you'll see a relationship between spaces and stars --
    namely: (2 * spaces) + stars = what?

    So, inside your outer for loop, just before your inner for loop, calculate spaceMax and use it in the for loop, then use this number and MAX (9) to calculate starMax:

    Java Code:
    public class Fu2 {
       private static final int MAX = 9;
    
       public static void main(String[] args) {
          for (int i = 0; i < MAX; i++) {
             int spaceMax = Math.abs(MAX/2 - i);
             for (int j = 0; j < spaceMax; j++) {
                System.out.print(" ");
             }
             
             int starMax = // [color="red"]*** use MAX and spaceMax to calculate this ***[/color]
             for (int j = 0; j < starMax; j++) {
                System.out.print("*");
             }
             System.out.println("");
          }
       }
    }

    Having said all this, you really don't need to use Math.abs, but instead could do all this with a simple if condition, but I think the Math.abs is cooler, and makes it easier to be able to create a diamond of any size.

    Luck!

    Fubarable, even though my problem is solved there is something that still confuses me. 2 * spaces + stars = middle line or MAX. I used this formula to get starMax. I thought you used the same formula to get spaceMax. But actually
    Java Code:
    spaceMax = Math.abs(MAX/2 - i);
    I understand that if it was
    Java Code:
    spaceMax = Math.abs(MAX  - i / 2);
    it would give me a kind of triangle. Not a diamond.
    But how did you find that the correct is
    Java Code:
    spaceMax = Math.abs(MAX/2 - i);
    , not something else?
    Thanks in advance.

  20. #20
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    It's all about generating equations from patterns. If we linearize the data by making it a straight line without a "reflection" like so:

    Java Code:
    x		y	
    ===================
    0		4		
    1		3		
    2		2		
    3		1		
    4		0		
    5		-1		
    6		-2		
    7		-3		
    8		-4
    We see that this is the plot of a line with slope -1 that intersects the y axis at 4 which mathematically means:

    y = -x + 4

    To make all negatives positive, I must take the absolute value of the right side:

    y = |4 - x|

    Substituting i for x and spaceMax for y and using the Java Math method for obtaining absolute value gives:

    Java Code:
    spaceMax = Math.abs(C - i);
    Where C is a constant that here = 4.

    Now when we play around with different values of MAX and check to see how this affects C we get:
    Java Code:
    MAX		C	
    ===================
    3		1		
    5		2		
    7		3		
    9		4		
    11		5		
    13		6
    we see that C = ((MAX - 1) / 2.0)
    but since int division tosses out any remainder, in Java, C is nothing more than MAX / 2

Page 1 of 2 12 LastLast

Similar Threads

  1. Nested Loops Study Help Needed
    By gysnewbie in forum New To Java
    Replies: 5
    Last Post: 07-12-2010, 09:14 AM
  2. Nested Loops for Java
    By soccer_kid_6 in forum New To Java
    Replies: 4
    Last Post: 02-21-2010, 06:27 AM
  3. nested for loops
    By Implode in forum New To Java
    Replies: 4
    Last Post: 09-01-2009, 09:47 AM
  4. Nested Loops
    By ks1615 in forum New To Java
    Replies: 4
    Last Post: 02-18-2009, 03:48 AM
  5. Nested loops?
    By gabriel in forum New To Java
    Replies: 4
    Last Post: 08-06-2007, 05:51 PM

Posting Permissions

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