TransWikia.com

How can i copy array elements from one to another in loop?

Stack Overflow Asked by eldlit on November 10, 2021

I am new to Java, but I’ve studied C for sometime and have very srupid question which i can’t answer on my own. I want to copy elements from one array( elements that come after number 10) to another( which will contain numbers after 10 from the first array) I have general idea how to make it, but i can’t find exact answer for my specific case. Maybe my code isn’t right and i should rewrite it, but i want to try to stick with it. I know there must be many answers for that exercise, but i am trying to avoid looking at them( because i want to start resolving them on my own) and create my own solutions.

My code does not copy each element( position) from 1st array, it copies the last element to all positions in the second array.

I hope i made my question clear and my code is readable. Thank you all in advance. Peace and love!

So, here comes the code

public class Main {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        int n; // Size of the first array
        int flag=0;

        System.out.println("Enter array size ");
        n=in.nextInt();

        int [] arr;
        arr=new int[n];
        
        System.out.println("Enter elements ");
        for(int i=0;i<n;i++){
            arr[i]=in.nextInt();
        }
        System.out.println("Your array is "+Arrays.toString(arr));

        for(int i=0;i<n;i++){

            if(arr[i]==10)
                break;
                 flag = arr[i]; // HERE I AM LOCATING 10'S POSITION
        }

        int size=n-flag; // This is a funny part, i am "calculating"  for the second array's size) 

        int[] new_arr;
        new_arr= new int[size];


        for(int i=flag;i<n;i++){ // I think here must be the problem! 
          for(int j=0;j<size;j++){
              new_arr[j]=arr[i];
          }

        }
        System.out.println("Lets try "+Arrays.toString(new_arr));


    }
}`

2 Answers

Well first, position 10 is position 10, no need to find the value at position 10...

There also no need for 2 loops, we just iterate on all the elements starting from 10 and copy them.

So we just do

int start_pos=10;
int size=n-start_pos;
int[] new_arr = new int[size];

for(int i=start_pos;i<n;i++){ 
      new_arr[i-start_pos]=arr[i];
  }
}

And yes like other said it, more generally you would use System.arraycopy() or even b better work with lists and call the subList method.

Answered by Nicolas Bousquet on November 10, 2021

you can just use System.arraycopy(source_arr, sourcePos, dest_arr, destPos, len); Its a method from java.lang.System

Answered by yanesof__ on November 10, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP