Numbers located in odd positions

Asked

Viewed 840 times

2

I should present only the numbers present in the odd vector positions, but I’m stuck:

package pag1;

import java.util.Scanner;
import java.util.Arrays;

public class ex1 {

    public static void main (String[] args){
        Scanner x = new Scanner (System.in);

        int posicao = 0;
        int[] numeros = new int[10];
        System.out.println("Digite 10 números inteiros seguidos:");

        while(posicao <= 9){
          numeros [posicao] = x.nextInt();
          posicao++;
        }

        System.out.println(Arrays.toString(numeros));       
    }

 }

When showing only the numbers that are in odd positions I don’t know how, just show all vector positions.

  • 1

    Start the counter position at 1 and add 2 in each iteration, so you go to positions 1, 3 ,5 ,7 ,9

2 answers

4


Loop starting from position 1 of your array and incrementing from 2 to position 7:

import java.util.Scanner;
import java.util.Arrays;

public class ex1 {

    public static void main (String[] args){

        Scanner x = new Scanner (System.in);

        int posicao = 0;
        int[] numeros = new int[10];
        System.out.println("Digite 10 números inteiros seguidos:");

        while(posicao <= 9){
        numeros [posicao] = x.nextInt();
        posicao++;
        }

        for(int i = 1; i < numeros.length; i+=2){
            System.out.println("indice: " + i + " = " + numeros[i]);
        }             
    }    
 }

See working on ideone: https://ideone.com/YWYb7p

Remember that arrays start from Indice 0, so your array goes from 0 to 9.

2

To show the odd or even value you can use as follows:

valor % 2 == 0 // retorna true para valores pares
valor % 2 != 0 //retorna true para valores impares

Using that expression inside a if, he tests the return of division by two is equal or different from zero

Your example could be with the following solution, using posicao to return all values in the odd positions or numeros[posicao] to return all the odd values saved in the array:

Scanner x = new Scanner(System.in);
int posicao = 0;
int[] numeros = new int[10];
while (posicao <= 9) {
   System.out.println("Digite o numero na possição vetor[" + posicao + "]:");
   numeros[posicao] = x.nextInt();
   posicao++;
}

posicao = 0;
while (posicao <= 9) {
    if (posicao % 2 != 0) {
        System.out.println("valor na posição impar do vetor:" + numeros[posicao]);
    }
    posicao++;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.