• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

recursion: print from 1 to n

 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 867
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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)
 
Ranch Hand
Posts: 155
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thank you
 
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic