Search code examples
javaalgorithmsum

writing a function that takes int n and returns the sum of odd less than n


Here is my code

public static int sumOfOddLessThan(int n)
{
    int iResult = 0;
    for(int i = n - 1; i > 0 && i % 2 != 0; i--)
    {
        iResult = iResult + i;
    }
    return iResult;
}

It does not work correctly, I dunno why :\

It should return 4 when I enter 5 but it returns 0


Solution

  • You're putting the condition i % 2 != 0 in the for loop instead of an if inside of the loop, hence if it's not met even once it breaks out of the entire loop.

    Your code should look like this:

    public static int sumOfOddLessThan(int n)
    {
        int iResult = 0;
        for(int i = n - 1; i > 0; i--)
        {
            if(i % 2 != 0) {
                iResult = iResult + i;
            }
        }
        return iResult;
    }
    

    Then again you don't even need a loop, you can evaluate it directly by getting the number of odd numbers lower than N and squaring that.