Skip to content
Advertisement

Java: Generate array from 1 to n with step size

I have trouble with a quite easy task. I want to have an array from 0 to a value n with step size t, always ending with n.

Example 1: n=10, t=3, array={0, 3, 6, 9, 10}

Example 2: n=20, t=5, array={0, 5, 10, 15, 20}

Example 3: n=1, t=1, array={0, 1}

I have code which I have been using for a while, but I found out there are some weird edge cases and its quite heavy to read.

int numOfElements = (int)(Math.ceil(n/2.0)+1);
int[] array = new int[numOfElements];

for(int pos=0; pos < numOfElements; pos++) {
    int val = t*pos;
    val = Math.min(val, n);
    array[pos] = val;
}

Is there a better solution for that?

Advertisement

Answer

Yes there is a standard and better way to do it. It’s called the step.

for(int pos = 0; pos < n; pos += t)

A for statement is broken up into three parts:

  1. The first part, int pos = 0 is code that is executed right before the for-loop starts.
  2. The second part, pos < n, is a bit of code that has to return a boolean value which is checked before every loop iteration to see if the loop should keep running or stop.
  3. And the third part is a bit of code executed after each iteration of the loop.

So technically, you can put any code you want into the three parts of the for statement, as long as the middle part returns a boolean. This allows you to increase or decrease the value by as much as you want.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement