Outputting odd numbers in Java

Question:

There is a method that outputs odd numbers from 1 to 100

public String printUnpared() {
    for (d = 1; d <= 100; d++) {
            if (d % 2 != 0)  {
                    unpared[d] = d;
            }

    }
    String stringUnpared = Arrays.toString(unpared);
    return stringUnpared;

And I get the output

[0, 1, 0, 3, 0, 5, 0, 7, 0, 9, 0, 11, 0, 13, 0, 15, 0, 17, 0, 19, 0, 21, 0, 23, 0, 25, 0, 27, 0, 29, 0, 31, 0, 33, 0, 35, 0, 37, 0, 39, 0, 41, 0, 43, 0, 45, 0, 47, 0, 49, 0, 51, 0, 53, 0, 55, 0, 57, 0, 59, 0, 61, 0, 63, 0, 65, 0, 67, 0, 69, 0, 71, 0, 73, 0, 75, 0, 77, 0, 79, 0, 81, 0, 83, 0, 85, 0, 87, 0, 89, 0, 91, 0, 93, 0, 95, 0, 97, 0, 99]

How to output odd numbers without zeros without using ArrayList? How do I start an array at 1 and not 0? You need to return via return, you cannot output via System.out.print.

Answer:

ArrayList can be used:

public String printUnpared() {
    List<Integer> unpared = new ArrayList<Integer>();
    for (d = 1; d <= 100; d+=2) {
      unpaired.add(d);
    }
    String stringUnpared = Arrays.toString(unpared.toArray());
    return stringUnpared;
}

Or calculate the odd number separately from the index:

    for (i = 0, d = 1; d <= 100; i++, d+=2) {
      unpaired[i] = d;
    }
Scroll to Top