1

I have to make a program that extract every 3th element from array. So far i have made the basic array, but im stuck at extracting every 3th element into separate array. How can i do that?

    public static void main(String[] args) {
    int min = -100;
    int max = 100;

    int[] array = new int[201];
for( int i = 0; i < array.length; i++) {

    array[i] = min + (int)(Math.random()*((max - min) + 1));
3
  • 3
    Check if it's divisible by 3, if it is then use it. Commented Dec 10, 2015 at 21:14
  • 3
    use mod, in java that is the % operator Commented Dec 10, 2015 at 21:17
  • 1
    With a for loop you can iterate through an array with whatever step you want. For instance for (int i = 0; i < array.length; i+=3) Commented Dec 10, 2015 at 21:19

2 Answers 2

2

To fill in a new array (named array2) with every 3rd item from your array:

int[] array2 = new int[array.length / 3];
int k = 2;
for(int j = 0; j < array2.length; j++) {
    array2[j] = array[k];
    k += 3;
}
Sign up to request clarification or add additional context in comments.

Comments

0

just make your for loop jump by three:

int[] newArray = new int[array.length / 3];
for (int i = 2 ; i < array.length ; i+=3) {
  newArray[i/3] = array[i];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.