Anonymous
Anonymous asked in Computers & InternetProgramming & Design · 4 weeks ago

Create a java for loop that prints the first five odd numbers in descending order.?

2 Answers

Relevance
  • 4 weeks ago

    Fully self-contained:

    for (int n : new int[] {9, 7, 5, 3, 1}) {

    System.out.println(n);

    }

    ...but that's not the way YOU are supposed to write it. I've used the "enhanced for loop" that is the best way to loop once for each value in an array or most other collection types, and the new-array-with-value-list syntax for creating what's effectively a constant list of values to loop over.

    You're better off learning how to use the regular for loop syntax:

    for ( <initialize>; <test>; <increment> } { <statements> }

    The <initialize> section is run just once, at the very beginning.

    The <test> condition is evaluated before every iteration of the body of the loop, including the first, and will halt the loop if it evaluates as false. It's possible for the condition to be false before the first iteration and not run the body at all.

    The <increment> expression will be run after the statements in the body on every iteration.

    The usual first pattern you learn is:

    for (int i = <first value>; i <= <last value>; ++i ) {...}

    That loops over values of i that increase by 1 each step because of that ++i at the end. (The majority of programmers prefer i++ to add 1 to i. I'm not the majority of programmers.)

    If you want to generate descending numbers, the pattern is almost the same:

    for (int i = <first value>; i >= <last value>; --i ) {...}

    That loop decreases the value of i on each iteration, and keeps looping until i is less than the end value.

    Whether increasing or decreasing, the way to generate only odd numbers is to (a) start on an odd number, then (b) add or subtract 2 in the <increment> section .

    You can use --i, --i (two decrements, separated by commas) to decrement by 2, or use the more common i -= 2 instead.

    For your program, it might help to know/remember that the nth odd number is (2n - 1).

  • Damien
    Lv 5
    4 weeks ago

    :sal

    echo 1

    echo 3

    echo 5

    echo 7

    echo 9

    goto sal

    • husoski
      Lv 7
      4 weeks agoReport

      @brilliant_moves: And, it asked for descending order. Oh well.

Still have questions? Get your answers by asking now.