1

TEST EXAMPLE:

b = 3

c = 19

constant = 4

Sum = 55

(3 + 7 + 11 + 15 + 19 = 55)

The logic is:Adding the numbers of an arithmetic line using recursive functioning

But my code outputs only the "return c" line

class Program
{
    static int Line(int b, int c, int constant, int sum)
    {

        if (b > c) return c;
        return (sum = sum + (Line(b+constant, c, constant, sum)));

    }
    static void Main(string[] args)
    {

        Console.WriteLine(Line(3,19,4,0));
        Console.ReadKey();
    }
}
1
  • 2
    If the point is to calculate the sum then I do see why you'd pass in a sum parameter. Commented Oct 21, 2015 at 14:12

2 Answers 2

3

After having debugging (just put break points and see what's going on), you can easily find two errors in your current implemtntation:

    static int Line(int b, int c, int constant, int sum) {
      if (b > c) 
        return sum; // return "sum", not "c"

      // "= b +" not " = sum +"
      return (sum = b + (Line(b + constant, c, constant, sum)));
    }
Sign up to request clarification or add additional context in comments.

4 Comments

Couldn't that just be return b + Line(b + constant, c, constant, sum); since the assignment to sum is obviously not used after the return?
@juharr: You're right return b + ... is a better choice (when evident for loop, IMHO, is the best one); my actual goal, however, was to point out that debugging (break points on both returns) can help to solve the problem easily.
it does really have to if (b > c) return sum;. because when you are in last stack value of sum is still 0. so you can make it if (b > c) return 0; and no changes.
@M.kazemAkhgary I agree, though I don't understand the point of passing in sum at that point. You could just add the result to whatever the "starting sum" is which the OP appears to pass in 0 anyway.
2

It doesn't look like you need to pass the sum in at all. In that case you can reduce it to one line if you want. Also you might want to pick more meaningful names for the parameters.

static int Line(int start, int end, int increment)
{
    return start > end? 0 : start + Line(start + increment, end, increment);
}

So the default case is when start > end you just return 0. Otherwise you add start to the next iteration which is adding increment to start and passing that into the recursive call.

Alternatively there is the none recursive solution

static int LineNonRecursive(int start, int end, int increment)
{
    int sum = 0;
    while (start <= end)
    {
        sum += start;
        start += increment;
    }

    return sum;
}

1 Comment

Nice implementation from ternary operator up to parameters' names, +1 from me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.