Question #116303

Here is a while loop that counts from 1 to 5 that demonstrates the 3 steps of writing a loop. Can you change it to count from 2 to 10? Can you make it count by 2s? Can you make it count backwards?public class LoopTest1

{

public static void main(String[] args)

{

// 1. initialize the loop variable

int count = 1;


// 2. test the loop variable

while (count <= 5)

{

System.out.println(count);

// 3. change the loop variable

count++;

}

Expert's answer

count from 2 to 10:


public class LoopTest1 {
    public static void main(String[] args) {
    // 1. initialize the loop variable
        int count = 2;
        // 2. test the loop variable
        while (count <= 10) {
            System.out.println(count);
            // 3. change the loop variable
            count++;
        }
    }
}

count by 2s:


public class LoopTest1 {
    public static void main(String[] args) {
    // 1. initialize the loop variable
        int count = 1;
        // 2. test the loop variable
        while (count <= 5) {
            System.out.println(count);
            // 3. change the loop variable
            count+=2;
        }
    }
}

count backwards:



public class LoopTest1 {
    public static void main(String[] args) {
        // 1. initialize the loop variable
        int count = 5;
        // 2. test the loop variable
        while (count >= 1) {
            System.out.println(count);
            // 3. change the loop variable
            count--;
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

LATEST TUTORIALS
APPROVED BY CLIENTS