A. Barrett - 1 year ago 67

Java Question

I'm trying to teach myself coding, and I stumbled on an example I don't understand. Could someone give me an overview of what this code is supposed to do? I'm a bit confused about int a[] and what is later int a[i]. I know what an array is, but could someone please explain how this is being used in this context? Thank you in advance.

`public class all {`

public int select(int a[],int n,int x)

{

int i=0;

while(i<n && a[i]<x)

{

if(a[i]<0)

a[i]=-a[i];

i++;

}

return(a[i-1]);

}

}

Answer Source

This

```
if(a[i]<0)
a[i]=-a[i];
i++;
```

is he same like this

```
if(a[i]<0) {
a[i]=-a[i];
}
i++;
```

`a[i]`

-> value at the position i, into the Array

`if(a[i]<0) {`

-> if the value at position i is smaller than 0, also negative number

`a[i]=-a[i];`

-> replace the value with a reverse sign.

`i++`

-> increment loop Counter

Also what is done here: negative numbers convert to positive numbers.

`while(i<n && a[i]<x) ->`

i = loop counter; if i smaller n and the value at position i in the array is smaller than x, then go into the loop.

`return(a[i-1]);`

-> return the last value, that has been checked into the while loop