RHS  =>  Allan => Prog2 Last update:  08/21/2003 19:12
WebMaster allanhn@rhs.dk

Recursion Assignment

Make a Java program that writes a positive number vertically on the screen. You can either hardcode the number (or numbers) into the program or make a program that reads the numbers from the keyboard (if you make a GUI then please make it simple...). Of course your method should work for ANY positive number.....

If the number is 346 the output should be:

  3
  4
  6

and if the number is 12543 the output should be:

  1
  2
  5
  4
  3

Hint: It seems as the problem is easy to solve: Just get the first digit in the number, write it, remove it from the original number and then perform the same algorithm for the remaining part of the number over and over until all digits have been written. The problem of course is to get that first digit. As you don't know how many digits there will be (remember: your method must work for any positive number...) it's actually difficult! The trisk is to "turn the problem upside down" and of course recursion will offer a neat solution......

 

 


Counter: