+ 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

26th Apr 2017, 6:09 PM
Prathamesh Jadhav
Prathamesh Jadhav - avatar
7 Respuestas
+ 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]); }
26th Apr 2017, 6:21 PM
Tashi N
Tashi N - avatar
+ 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.
26th Apr 2017, 6:27 PM
Tashi N
Tashi N - avatar
+ 10
You're welcome.
26th Apr 2017, 6:35 PM
Tashi N
Tashi N - avatar
+ 9
You mean the whole array? for (int i : yourArray) System.out.println(i);
26th Apr 2017, 6:31 PM
Tashi N
Tashi N - avatar
26th Apr 2017, 6:24 PM
Meharban Singh
Meharban Singh - avatar
+ 1
Yes. I forgot. Printed it using this for( int j=0;j<n.length;j++){ System.out.print(n[j]) ; } Thanks.
26th Apr 2017, 6:35 PM
Prathamesh Jadhav
Prathamesh Jadhav - avatar
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
26th Apr 2017, 6:29 PM
Prathamesh Jadhav
Prathamesh Jadhav - avatar