Saturday, April 24, 2010

Java recursive method  

0 comments

Sometime we need to solve a problem using the same way. For example you need to build a program that will print number from 1 until number that input by a user. First program will print number without using recursive technique and second program we will use recursive technique to print number from 1 until number that input by a user.You should see how a recursive method will do the same thing until problem solve.


  1. import java.util.Scanner;
  2. public class Test
  3. {
  4. public static void main(String[]args)
  5. {
  6. Scanner s=new Scanner(System.in);
  7. System.out.println("Put a number");
  8. int a=s.nextInt();
  9. System.out.println("IT'S RESULT");
  10. System.out.println("***************");
  11. for(int i=1;i<=a;i++)
  12. {
  13. System.out.println(i);
  14. }
  15. }
  16. }


SECOND PROGRAM :
print method in PrintNumber class is example of recursive method.


  1. import java.util.Scanner;
  2. public class Test
  3. {
  4. public static void main(String[]args)
  5. {
  6. Scanner s=new Scanner(System.in);
  7. System.out.println("Put a number");
  8. int myNumber=s.nextInt();
  9. PrintNumber pn=new PrintNumber();
  10. System.out.println("IT'S RESULT");
  11. System.out.println("***************");
  12. pn.print(myNumber);
  13. }
  14. }
  15. class PrintNumber
  16. {
  17. public void print(int a)
  18. {
  19. if(a==1)
  20. {
  21. System.out.println(a);
  22. }
  23. else
  24. {
  25. int temp=a-1;
  26. print(temp);
  27. System.out.println(a);
  28. }
  29. }
  30. }


For example if you put 2 into second program, when it enter print method in PrintNumber class, firstly program will check if the number is 1 or not. If not, the number will be minus with 1 before it send it's result to print method again. In this case it will send 1 to print method. So System.out.println(a) for a=2 will stop for a while until a=1. Now after it send 1 to print method, condition for a==1 will be true. 1 will be print, and System.out.println(a) for a=2 will continue again by print 2.

I hope it will help.

What next?

You can also bookmark this post using your favorite bookmarking service:

Related Posts by Categories



0 comments: to “ Java recursive method

Extension Factory Builder