Nate
Nate

Reputation:

Why does this code add 1 to the result?

If if (n > 0) it returns a normal result, however if (n >= 0) it returns the normal result + 1, which I don't understand because 0 * 0 = 0. If anyone knows why this does this I would love to figure this out.

import java.util.*;

// Recursive method returns sum of first n squares
public class RecursiveSum
{
    public static void main(String[] args)
    {
        while (true)
        {
            Scanner keyboard = new Scanner(System.in);

            System.out.println("Enter a number:\tIf you want to exit, enter a negative number.");

            int n = keyboard.nextInt();

            if (n < 0)
                System.exit(0);

            System.out.println("sum(" + n + ") = " + sum(n));
        }
    }

    public static int sum(int n)
    {
        int sum2 = n * n;

        if (n >= 0)
            sum2 += sum(n - 1);

        return sum2;
    }
}

Upvotes: 1

Views: 185

Answers (1)

P&#233;ter T&#246;r&#246;k
P&#233;ter T&#246;r&#246;k

Reputation: 116296

if(n>=0) makes the method call itself recursively with -1 as a parameter. And sum(-1) == -1 * -1 == 1.

Upvotes: 8

Related Questions