I was trying to understand the solution to this problem. The question is to see if any three numbers in an array return a certain value. This answer is what I found online.
public bool numberequal(int sum, int[] array)
{
int i, k, j;
bool answer = false;
for (i = 0; i < array.Length - 2; i++)
{
for (k = i + 1; k < array.Length - 1; k++)
{
for (j = k + 1; j < array.Length; j++)
{
if (array[i] + array[k] + array[j] == sum)
{
answer = true;
return true;
}
}
}
}
return answer;
}
My questions was for the i iteration of the first loop have -2 on array.length. The second k iteration has -1 as well. Could someone be kind enough to explain why? Don't we need to loop over every element to get the correct answer?