• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

recursion: print from 1 to n

 
Fendel Coulptz
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
as you all can see im very new to java and recursion here...

"Given an integer n, write recursive function that prints 1 through n"

i can easily do it with a method with 2 variables, eg. display(int m, int n),

but how can i do it with only a single variable? eg. display(int n)

thanks.
 
Francis Siu
Ranch Hand
Posts: 867
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
i can easily do it with a method with 2 variables, eg. display(int m, int n),
Could you post the program here? As we know, you can do with 2 variables, some edit are needed to do with only one variable.
Following structure is used for writing recursion

HTH
 
Fendel Coulptz
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oops sorry i meant parameters not variables so sorry

method is display(int m, int n)

so to print "12345678910" from one to 10 is display(1,10)
 
Elouise Kivineva
Ranch Hand
Posts: 154
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't see the answer either.
Are you sure you aren't supposed to print numbers from n to 0?
 
Joyce Lee
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Fendel,
but how can i do it with only a single variable? eg. display(int n)



Joyce
 
Fendel Coulptz
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think this is called "tail recurssion". You should be able to easily revise it to use so-called "head recurssion" in order to print the numbers from n down to 1.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic