This is the code. I tried to solve it, but I can\'t understand how its output is 111111?
public class Test {
public static void main(String[] args) {
If you're new to programming, print debugging can be a really great way to learn what is going on in your program. I've put in a bunch of print statements on your program, try running it and see if you can understand the results:
public class Test {
public static void main(String[] args) {
int list[] = {1, 2, 3, 4, 5, 6};
for (int i = 1; i < list.length; i++) {
System.out.println("\n\n\nloop number " + i);
System.out.println("\ni = " + i);
System.out.println("\nThe value at list[i] = " + list[i]);
System.out.println("\ni - 1 = " + (i - 1));
System.out.println("\nSo I'm accessing element " + (i - 1) +
" in the list for this iteration.");
System.out.println("\nThe value at list[i - 1] = " + list[i - 1]);
System.out.println("\nEnd of loop " + i);
list[i] = list[i - 1];
}
for (int i = 0; i < list.length; i++)
System.out.print(list[i] + " ");
}
}
I generally wouldn't use that many for a simple loop, but I wanted to show you different ways of accessing the values as the loop was running.
You will get something like this for each iteration of the loop in your console, it walks you through what the values are:
loop number 1
i = 1
The value at list[i] = 2
i - 1 = 0
So I'm accessing element 0 in the list for this iteration.
The value at list[i - 1] = 1
End of loop 1