Adnan Azmat
Adnan Azmat

Reputation: 33

Increase elements of array in a certain interval by a certain amount. JAVA

I have an array A of size N. I have there integers S, E and I. I need to increment all array elements from index S to E by I.

Values of S and E are guaranteed to be logically correct

My attempt:

for(int i=S; i<=E; i++)
{
A[i]=A[i]+I;
}

Is there a faster way to do the same?

Upvotes: 1

Views: 853

Answers (2)

albert_nil
albert_nil

Reputation: 1658

you are not ensuring no error if S or E are greater than N.

i would do:

for (int i=S; i<=E && i<N; i++) {
    A[i] += I;
}

Also, be sure you are interested in element between S and E, with E being included (talking about the = on the condition to end the loop).

Aside from that, i see no better option in terms of being faster.

Upvotes: 1

John3136
John3136

Reputation: 29266

No. Your approach is correct. You could do A[i] += I but there is no change you can make to speed it up by "orders of magnitude"

Upvotes: 1

Related Questions