Reputation: 15091
When iterating through an array how do you compare the current element to the previous one? This is easy except for the caveat the first element has no previous one. Is the best solution
for(i = 0; i < arrLen; i++)
{
arr[i] = process(i, someArg);
if(i > 0)
someFunc(arr[i], arr[i-1]);
}
This is one more comparison that needs to be performed for each element of the array which seems wasteful.
Sorry I forgot to say the array is being populated at the same time. So starting the loop at 1 would mean the first element is left empty.
Upvotes: 2
Views: 845
Reputation: 2962
Start your loop at 1 instead of zero, then you will always have an i-1
for(i = 1; i < arrLen; i++)
someFunc(arr[i], arr[i-1])
EDIT:
Given your new information, I'd say just leave it with the if statement as you have it. I don't think there is a particularly better way. You could initialize a prevVal variable outside of the loop, but I don't think you'd really gain a lot over the if i > 0 statement you have.
Upvotes: 0
Reputation: 8956
You just need to start iteration not from 0 but from 1. It is because 0-1=-1
(illegal array index)
for (int i = 1; i < arrLen; i++)
someFunc(arr[i], arr[i-1]);
And assignment of zeroth element should be done before loop:
arr[0] = process(0, someArg);
for(i = 1; i < arrLen; i++)
{
arr[i] = process(i, someArg);
someFunc(arr[i], arr[i-1]);
}
And also you may need to check if there is need to assign zeroth element so code should be:
if (arrLen)
{
arr[0] = process(0, someArg);
for(i = 1; i < arrLen; i++)
{
arr[i] = process(i, someArg);
someFunc(arr[i], arr[i-1]);
}
}
NOTE: in this way you don't need to use if
condition because i
always positive.
Upvotes: 0
Reputation: 225272
Just start the loop at 1:
for (int i = 1; i < arrLen; i++)
someFunc(arr[i], arr[i-1]);
Edit: Given your new loop, I think your code is OK. Your optimizer will likely handle it just fine. If you're really concerned, just do the first assignment outside the loop:
arr[0] = process(0, someArg);
for(i = 1; i < arrLen; i++)
{
arr[i] = process(i, someArg);
someFunc(arr[i], arr[i-1]);
}
Upvotes: 4
Reputation: 1785
i quess you have for
in actual code
for( int i = 1; i < arrLen; i++)
someFunc(arr[i], arr[i-1]);
or
for( int i = 0; i < arrLen -1; i++)
someFunc(arr[i], arr[i+1]);
Upvotes: 1
Reputation: 12985
If you are going to do that, just start the counter at 1.
for (int i = 1 ...)
If you are doing it the other way, with an i+1
, end the counter 1 sooner
for (int i = 1; i < arrLen -1 ; ++i)
Upvotes: 1