-1

Can someone tell me what is this function doing? I just know that it returns the sum of x + y, but I want to know why. Thanks

    public static int f(int x, int y){
    while( y > 0){
        x = x + 1;
        y = y - 1;
    }
    return x;
}
Teemo
  • 111
  • 2
  • 8

3 Answers3

3

There are two cases:

First case: y <= 0
Because the while loop is false, it just returns x ("it skips the part")

Second case: y > 0
Because the while loop is true, it returns x + y (x + number of iterations)

The number of iterations is the value of y because with every iteration, y will be decreased by 1 until y = 0.

Luca Jung
  • 1,313
  • 10
  • 23
0

The loop starts at the value of y, and decrements it on each iteration, stopping when y gets to zero.

For each of these iterations, 1 is added to x. Therefore, for 'unit' of y, a 'unit' is added to x.

Edit As noted in the comments, the function will not return the sum of the two numbers if y is less then zero, since the loop will not execute at all.

Ben Wainwright
  • 2,367
  • 10
  • 26
  • You're assuming that `y` begins with a value greater than zero. As Dmitry Bychenko points out in his comment, if `y` begins with a value of zero or less than zero then nothing is added to `x` and the original value of `x` is returned. – Bobulous Oct 16 '16 at 19:10
-1

Addition can be viewed as a series of increments. That's what this function does. It increments x y times and returns the result which is x + y. It is assumed that y is a natural number.

Frank Puffer
  • 7,773
  • 2
  • 16
  • 39
  • Could anyone explain the downvotes and the delete request? I don't get it. – Frank Puffer Oct 16 '16 at 19:19
  • I don't know, I think your answer is also useful. I gave you +1 – Luca Jung Oct 17 '16 at 13:25
  • 1
    I downvoted because, as other comments and answers have explained, the method does not always return `x + y`, so to state that it returns this is incorrect. If you get downvotes then delete or modify your answer to address any problems like this. (Of course, if you check an answer carefully and decide it's fine as it is then you should just ignore the downvotes.) – Bobulous Oct 22 '16 at 13:23
  • @Bobulous: "...modify your answer to address any problems like this." But that's what I did. – Frank Puffer Oct 22 '16 at 14:37
  • 1
    It still doesn't read right to me. The method does not assume that `y` is greater than zero, it performs an explicit check to determine whether or not it is greater than zero. – Bobulous Oct 22 '16 at 19:56