Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

115
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda