Results 1 to 2 of 2
  1. #1
    melody is offline Member
    Join Date
    Oct 2009
    Posts
    3
    Rep Power
    0

    Question recursive method problem

    a) What is the output of the following recursive code?

    public static void main(String[] args){
    System.out.println(foo(4));
    }

    public static int foo(int n){
    System.out.println(n);
    if (n == 0)
    return n;
    else
    return n + foo(n - 1);
    }

    b) Write a recursive method that accepts a single String as a parameter and returns ther reverse of that String. For example, calling the method reverse("Test")would return the String "tseT."



    My answer is these? are those right? thank you
    (a)
    4
    3
    2
    1
    0
    10

    (b)
    public static String reverse(String str) {
    if (str == null || str.length() == 0)
    return null;
    else if (str.length() == 1) {
    return str;
    } else
    return str.charAt(str.length() - 1)+reverse(str.substring(0, str.length() - 1));
    }

  2. #2
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    8

    Default

    Again you can run those snippets and see the results for yourself.

Similar Threads

  1. Recursive method using int array, help needed
    By chupalo17 in forum New To Java
    Replies: 4
    Last Post: 09-07-2009, 11:15 PM
  2. Java Recursive method problem
    By kj2009 in forum Advanced Java
    Replies: 2
    Last Post: 02-25-2009, 03:19 PM
  3. exercise of recursive method
    By amexudo in forum New To Java
    Replies: 2
    Last Post: 03-09-2008, 05:55 PM
  4. Replies: 1
    Last Post: 02-16-2008, 09:10 PM
  5. Recursive Method
    By bluegreen7hi in forum New To Java
    Replies: 5
    Last Post: 11-29-2007, 04:45 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •