hhhh
hhhh

Reputation: 137

How can i do the same thing using For loops instead of while?

I need to modify the program so that for all values of k that are larger than or equal to 0, the program works as it did before, but for all values of k less than 0, the program displays, k, k-1, k-2, … 0. You can only use for loops. So my code is this, using while loops,

     while (i != k && k > 0) {
         i = i + 1;
         System.out.println(i);
     }
     while (k <= 0) {
         System.out.println(k);
         k = k + 1;
     }

I successfully did it for the positive numbers, but I am having issues with negatives.

here is the for loop i wrote for the positives

    for (int i = 0; i <= k; i = i + 1) {
        System.out.println(i);
    }

please help!!!!

Upvotes: 1

Views: 124

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201437

The Oracle documentation for The for Statement says (in part)

The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:

 for (initialization; termination; increment) {
     statement(s)
 }

When using this version of the for statement, keep in mind that:

  • The initialization expression initializes the loop; it's executed once, as the loop begins.
  • When the termination expression evaluates to false, the loop terminates.
  • The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.

tl;dr you could do something like

for (; i != k && k > 0;) {
    System.out.println(++i);
}
for (; k <= 0; k++) {
    System.out.println(k);
}

Upvotes: 2

Related Questions