Search code examples
javaarraysuser-input

Printing Odd and Even Elements of an Array


I'm trying to write a program that reads a sequence of integers and divide it into two sequences. The values on odd positions will be the first sequence and the values of even positions will be the second sequence. The program prints the elements of the first sequence and then the elements of the second sequence separated by a single space. The first input value specifies the number of elements.

Input: 7 1 2 4 5 6 8 9

Expected Output: 1 4 6 9 2 5 8

My Output: 2 0

package twosequences;

import java.util.Scanner;

public class TwoSequences {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int[] values = new int[n];
    for (int i = 0; i < values.length; i ++) {
        values[i] = sc.nextInt();
    }
    int odd = 0;
    int even = 0;
    int i = 1;
    if (i % 2 == 0) {
        even = values[i];
    } else {
        odd = values[i];
    }
    i++;
    System.out.printf("%d %d%n", odd, even);        
  }


}

I'm not sure why I'm outputting 2 0. Any suggestions?


Solution

  • You need two different loops to iterate over even and odd elements respectively to obtain the desired output.

    for (i = 0 ; i < n ; i += 2) {
        even = values[i];
        System.out.printf("%d ", even);
    }
    for (i = 1 ; i < n ; i += 2) {
        odd = values[i];
        System.out.printf("%d ", odd);
    }
    

    Hope this helps.