0

how can i change this code into while loop. I'll convert it into a while loop

public class example {
    public static void main(String[] args) {
        int [] numbers={10, 20, 30, 40, 50};
        for(int x:numbers){
            if(x==30){
                break;
            }
            System.out.print(x);
            System.out.print("\n");
        }
    }
}
1
  • Just get the iterator of the array, loop as long as hasNext() returns true and get the element using next() in the loop. Or use an index. Commented Dec 17, 2020 at 5:50

1 Answer 1

1
    int[] numbers = {10, 20, 30, 40, 50};    
    int i = 0;                               
    while (i < numbers.length) {             //iterating till the last element in the array on index
        int currentValue = numbers[i];       //storing in a variable for reuse while printing the value
        if (currentValue == 30) {            //conditional break in the loop as OP
            break;
        }
        System.out.println(currentValue);    //printing each element in a newline
        i++;                                 //incrementing the counter to the next index
    }

Output:

10
20
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.