Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

116
Views
For loop isn't returning -1 when I want it to as per the conditions

The issue is that when an integer lesser than or equals to 0 is passed as a parameter for 'end', and when 'end' is lesser than 'start' it doesn't return -1.

    public static boolean isOdd (int number)
    {
        if (number < 0)
        {
            return false;
        }
        else
        {
            if (number % 2 != 0 )
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }

This is method to test the parameter 'start' and 'end'

    public static int sumOdd (int start, int end)
    {
        
        int sum = 0;
        for (int i = start; i<=end; i++)
        {
            if ((start<=0) || (end<=0) || (end<start))
            {
                return -1;
            }
            else
            {
                if (isOdd(i))
                {
                    sum+=i;
                }   
            }
        }
        return sum;
    }
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

The problem lies in your for loop.

You instructed the loop to run when i was smaller or equal to end. That's sounds good on paper, but you do realize that this statement

if ((start<=0) || (end<=0) || (end<start))

will never be run (in the case that end is larger than start), since i is start, and if end is bigger than start, it is therefore bigger than i, which wouldn't satisfy your previous defined condition in the for loop, i is smaller or equal to end. Therefore, the for loop will never run.

You should be doing:

public static int sumOdd(int start, int end) {
        int sum = 0;
        if ((start <= 0) || (end <= 0) || (end < start)) {
            return -1;
        } else {
            for (int i = start; i <= end; i++) {
                if (isOdd(i)) {
                    sum += i;
                }
            }
            return sum;
        }
    }

Test Run

sumOdd(1, 0) returns -1

sumOdd(1, 3) returns 4

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!