• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java program that prints specific numbers in pattern  RSS feed

 
Birel Chowdhury
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Write a java program that prints 0..........121..........23432..........3456543............456787654............56789098765 in this pattern?

My code:

Please advise how can I improve?


 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37507
552
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Birel,
I think the biggest improvement would be to use more meaningful variable names. "i" is typically used as a loop counter so that one is apparent. And "n" is clear as the max value. (Although you could name it that.)

"r" looks like a simple loop counter as well. "j" and "k" are common conventions for that. Then there is "k". I'm not sure what it is used for. Think about what the purpose of it is. And remember that unlike in algebra, programmers can use whole words as variable names

Also, try to develop the habit of getting rid of this line when you write code:
// TODO Auto-generated method stub
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Birel Chowdhury wrote:Please advise how can I improve?

Well, one thing I'd suggest (other than Jeanne's excellent advice) is to put lines 14-19 in a method, viz:and then call THAT method whenever you want to print out one of your "numbers".

Winston
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Birel Chowdhury wrote:Please advise how can I improve?

Your loop at line 21 could also be "simplified" a bit, viz:HIH

Winston
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Birel Chowdhury wrote:Please advise how can I improve?

Finally, since you know that the first thing you're going to print out is "0", you could simplify the whole thing by starting your loop from the next stage, viz:but some might regard that as "cheating".

You could also declare 'k' in the loop, since you never use it outside, ie:

  for(int k = 1, n = 2; n <= 10; n = n+2, k++) { ...

HIH

Winston
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!