Ryp
Ryp

Reputation: 3

For loop to While loop Java

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");
        }
    }
}

Upvotes: 0

Views: 168

Answers (1)

Saif Ahmad
Saif Ahmad

Reputation: 1171

    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

Upvotes: 1

Related Questions