+ 1
Can anyone explain the following code
Got this code in a challenge. But I'm not able to connect the logic. Can anyone please explain. https://code.sololearn.com/cooTD3Aj344F/?ref=app
7 ответов
+ 13
int[] n={0,1,0,-1};
// loop over the array,
// starting at the 2nd value
for (int i=1;i<n.length;i++) {
// if the element is zero
// and the element before it is not zero
if(n[i]==0 && n[i-1]!= 0){
// assign the value of the element
// before this to x
int x= n[i-1];
// assign the actual element's value
// to the element before it
n[i-1]= n[i];
// assign the value of x to the
// actual element
n[i]= x;
// print the third element of the array
System.out.print(n[2]);
}
+ 11
The if statement is only true for the 3rd element of the array.
So,
x is 1
n[1] is set to 0
n[2] is set to x which is 1.
1 is the output.
+ 10
You're welcome.
+ 9
You mean the whole array?
for (int i : yourArray)
System.out.println(i);
+ 1
Yes. I forgot. Printed it using this
for( int j=0;j<n.length;j++){
System.out.print(n[j]) ;
}
Thanks.
0
Ok thanks a lot Tashi. That helped. Could you help me out with one more thing. What do I have to do to print the new array? Thanks in advance