+ 1
Why this program prints "000" and not "123"
public class Program { public static void main(String[] args) { int arr[]={1,2,3}; int arrr[]=arr; for(int i=0;i<3;i++) arr[i]=0; for(int i=0;i<3;i++) System.out.print(arrr[i]); } } https://code.sololearn.com/cN6kVFHZNV7a/?ref=app
4 Antworten
+ 3
Nicolae Dubenco No you didn't copy the array. You have just assigned the reference of arr to another arrr means initialized the arrr which is actually not coping the elements. To copy the array do this in 1st loop
arrr[i] = arr[i];
________________________________
First Approach to copy array
--------------------
int arr[] = {1,2,3};
int arrr[] = arr;
for(int i = 0; i < 3; i++)
arrr[i] = arr[i];
for(int i = 0; i < 3; i++)
System.out.print(arrr[i]);
__________________________________
Second Approach to copy array
-------------------------------
int arr[] = {1,2,3};
int arrr[] = new int[arr.length];
arrr = arr;
for(int i=0;i<3;i++)
System.out.print(arrr[i]);
+ 4
Because you are assigning value with 0 in 1st loop.
change arr[i]=0 with arr[i]= i + 1
+ 2
Thanks a LOT for help. Now i understand👍
+ 1
Ok, but i print the second array which copied the first array with 123 before the loop, whats wrong?