Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

117
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda