+ 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

6th Jun 2020, 7:49 AM
Nicolae Dubenco
Nicolae Dubenco - avatar
4 odpowiedzi
+ 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]);
6th Jun 2020, 8:02 AM
A͢J
A͢J - avatar
+ 4
Because you are assigning value with 0 in 1st loop. change arr[i]=0 with arr[i]= i + 1
6th Jun 2020, 7:50 AM
A͢J
A͢J - avatar
+ 2
Thanks a LOT for help. Now i understand👍
6th Jun 2020, 9:04 AM
Nicolae Dubenco
Nicolae Dubenco - avatar
+ 1
Ok, but i print the second array which copied the first array with 123 before the loop, whats wrong?
6th Jun 2020, 7:56 AM
Nicolae Dubenco
Nicolae Dubenco - avatar