kindal
kindal

Reputation: 29

logic to print a number series 1,n,2,n-1,3,n-2,... series should be 1 to n(the input given)

I'm trying my hands on basic programming and I came across this question. I have a function with a return type as string, that takes an integer input and has to print the series mentioned. Here's what I did.

String s=new String("h");
int[] a=new int[n];
int k=1;
for(int i=0;i<n;i+=2)
{
  a[i]=b;//line6
  a[i+1]=n-(b-1);//line7
  b++;
} 
s=Arrays.toString(a);
return s;

When I enter an "even" no. like 4. I get the proper result [1,4,2,3].

But when I enter "odd" no. like 5. I get an ArrayOutOfBoundException

I Know where Im going wrong at line6 and line7 but I'm not getting an idea how to modify it accordingly.

I also wish to return the string as 1 n 2 n-1 3 n-2 ... instead of [1,n,2,n-1,3,n-2,..]

Upvotes: 2

Views: 1528

Answers (4)

user4668606
user4668606

Reputation:

Split the problem up into two smaller problems:

Generating all values for even indices

for(int i = 0; i < a.length; i += 2)
    a[i] = i + 1;

Generating all values for odd incides

for(int i = 1; i < a.length; i += 2)
    a[i] = n - i / 2;

Thanks to integer-division i / 2 of an odd number can substitute (i - 1) / 2.

Full code

int[] a = new int[n];

for(int i = 0; i < a.length; i += 2)
    a[i] = i + 1;

for(int i = 1; i < a.length; i += 2)
    a[i] = n - i / 2;

return Arrays.toString(a);

Upvotes: 0

MBo
MBo

Reputation: 80297

consider the next approach:

for(int i=0;i<n/2;i++)
{
   a[2*i] = i+1;
   a[2*i+1] = n-i;
} 
if (n&1==1)  //how to check for oddity in Java?
  a[n-1] = (n+1)/2

Upvotes: 1

luk2302
luk2302

Reputation: 57184

The inside of your loop should look like

a[i] = b;
if (i + 1 < n) { // check the bounds before writing at i+1
    a[i + 1] = n - (b - 1);
}
b++;

The reason for that is that when having odd numbers (e.g. 5) i gets to become 4 in the last iteration of the loop, 4 is smaller than 5, therefore the code enters the loop, then you access a at index 4, which is okay, but then you try to access it at 4+1, which is 5, but the array does not have an index 5 because.

Upvotes: 0

John Bupit
John Bupit

Reputation: 10618

That's because you have a loop running from i = 0 to i < n, and you are trying to access a[i + 1]. This runs fine on even numbers because you're incrementing 2 each time, and the last iteration checks for a[n - 2] and a[n - 1].

The ArrayIndexOutOfBoundException occurs on odd numbers, however, because the last iteration attempts to access a[n - 1] and a[n].

One way to modify the loop would be to increment only by 1, and set the value of a[i] by checking the parity of i inside the loop:

for(int i = 0; i < n; i++, b++) {
    a[i] = (i % 2 == 0)? b: (n - (b - 1));
} 

Upvotes: 1

Related Questions