Results 1 to 2 of 2
  1. #1
    Join Date
    Oct 2003
    Posts
    138

    Unanswered: What is error in the following recursive method?

    What is error in the following recursive method?
    Int sum (int n)
    {
    If (n == 0)
    Return 0;
    Else
    Return n + sum (n);
    }

  2. #2
    Join Date
    Mar 2004
    Posts
    16

    Re: What is error in the following recursive method?

    Originally posted by valexena
    What is error in the following recursive method?
    Int sum (int n)
    {
    If (n == 0)
    Return 0;
    Else
    Return n + sum (n);
    }
    It's a loop... you never incremnet/decrement/modify n, so you don't perform any recursive step... Just think if n=2... return 2+sum(2)+sum(2)+sum(2) + ... and so on for an infinite number of times!!!!

    it could look like this:

    public int sum (int n)
    {
    if (n == 0)
    return 0;
    else
    {
    if (n>0) return n + sum (n-1);
    else return n + sum(n+1);
    }
    }

Posting Permissions

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