Trace the flow of the loop in the code shown below with the
Trace the flow of the loop in the code shown below with the values array containing 32, 54, 67.5, 29, 35. Show two columns, one with the value of iand one with the output.
for (int i = 0; i < values.length; i++) {
if (i > 0) {
System.out.print(\" | \");
}
System.out.print(values[i]);
}
Solution
//Demo program to run the code in java
public class ForLoopTest {
public static void main(String args[]){
double values[]= {32, 54, 67.5, 29, 35};
for (int i = 0; i < values.length; i++) {
if (i > 0) {
System.out.print(\" | \");
}
System.out.print(values[i]);
}
}
}
----------------output----------------
32.0 | 54.0 | 67.5 | 29.0 | 35.0
---------------- output test----------------
Explanation
Value of i Output value Explanation
0 32.0 this is the first iteration hence i=0, the value in 0th index is 32.0, After this the index i increments to 1;
1 54.0 this is the Second iteration hence i=1, the value in 0th index is 54.0, After this the index i increments to 2;
2 67.5 this is the first iteration hence i=0, the value in 0th index is 67.5 After this the index i increments to 3;
3 29.0 this is the first iteration hence i=0, the value in 0th index is 29.0 After this the index i increments to 4;
4 35.0 this is the first iteration hence i=0, the value in 0th index is 35.0 After this the index i increments to 5 which will terminate the for loop and the main program;
//Note: please feel free to ask doubts. God bless you!!
