215k views
2 votes
int[ ] values = {150, 34, 320, 2, 11, 100}; for (int i=0; i < ; i++) { if (values[i] % 10 == 0) System.out.println(values[i] + " is divisible by 10"); } which for-each loop would produce the same output?

User SIM
by
7.4k points

1 Answer

3 votes

Final answer:

The for-each loop equivalent of the provided for loop in Java would be: 'for (int value : values) { if (value % 10 == 0) System.out.println(value + " is divisible by 10"); }' It iterates through each element of the 'values' array and prints elements divisible by 10.

Step-by-step explanation:

The student has asked how to rewrite a traditional for loop that uses array indexing to a for-each loop in Java. The original loop iterates through an array of integers, checks if each integer is divisible by 10, and prints those that are.

A correct for-each loop that would produce the same output is:

for (int value : values) { if (value % 10 == 0) System.out.println(value + " is divisible by 10");}

This loop uses a for-each construct to iterate directly over each element in the 'values' array without using an index variable.

User Mingye Wang
by
8.1k points
Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.