• Post Reply Bookmark Topic Watch Topic
  • New Topic

Nested For Loop  RSS feed

 
Paul D Pearson
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Having trouble with nested for loops
This is what I want:


This is what I'm getting, can't seem to figure out how to decrease the space and add a number:



 
Junilu Lacar
Sheriff
Posts: 11493
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This a pattern analysis problem. Go through the example I gave here: https://coderanch.com/forums/posts/preList/673821/3165038#3165038 -- it's a series of posts to go through the process of printing out a diamond pattern of #s.  Pay attention to the parts where I draw up a table of numbers to help discern a pattern.
 
Piet Souris
Master Rancher
Posts: 2044
75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why not work top down? As you can see, every line has two spaces more than its successor. So, lets start with an array of length 'maxInteger + 1'. We know that that last element, array[maxInteger],  starts with no spaces, therefore array[maxInteger] = "".
Now go from maxInteger - 1 to 1, adding two spaces to the array element of the successor as you go. You now have the spaces correct.

Next, it is time to add the strings of integers to the created strings. We must make strings of the form "1", "333", et cetera, so a method like 'String createRepeatedString(String stringToRepeat, int numberOfRepeats) would come in handy.

Having that method, it should then be a doddle to get the wanted output.
 
Paul D Pearson
Greenhorn
Posts: 11
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the help!  I added another loop after the nested to complete the assignment. 
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!