# A better solution to my problem

This is a discussion on A better solution to my problem within the C Programming forums, part of the General Programming Boards category; Hi All, First post here Would like some help for a short problem. I have two arrays of the same ...

1. ## A better solution to my problem

Hi All,

First post here Would like some help for a short problem.

I have two arrays of the same size. I need to find if the difference of n consecutive elements of the two arrays are bigger than a certain threshold.

I have a rudimentary solution to this but was wondering if someone has a better and smarter solution. In the case of n=3, I am doing:

Code:
```for (int i = 0; i <= array_size; i++ ){
if ((a[i]-b[i] >= thresh ) && (a[i+1]-b[i+1] >= thresh) && (a[i+2]-b[i+2] >= thresh))
// do something
}```
(Please ignore the part where I reach the end of the array. I have presented my problem to focus on the part above only)

As you can see, the conditional statement for the if is very poor design. If n = 10, I would have to write a very long expression.

Does someone have a better solution than mine?

2. I would use the "for()" loop simply to check for the desired condition, with a flag to indicate this condition. Then after the loop, have code to perform certain actions based on the status of this flag.

Code:
```for i = 0 until i < array_size
if array1[i] - array2[i] >= threshold
increment counter
else
clear counter

if counter >= n
set flag
end for

if flag == 1
// do something```
Note that on line 2 in my example, which was borrowed from your example, you should compare with the absolute value of the difference, in case array 2 happen to contain a larger value than array 1.

Also note that if "array_size" is the size of your array, you're overruning the bounds of that array:

Code:
`for (int i = 0; i <= array_size; i++ )`
Array indices start at zero and go to N-1. The standard way of representing this would be:

Code:
`for (int i = 0; i < array_size; i++ )`

3. I'd be inclined to use logical statements that could break away from the "for" loop as soon as a difference was detected.

Code:
```    for (i = 0, flag = 1; (i < arr_size) && (flag != 0); i++)
{
flag &= (arr1[i] == arr2[i]);
}```
arr1[i] == arr2[i] will equate to 1 if true, or 0 if false
flag &= result -> flag will be 1 if result is 1, 0 if false
If you look at the condition in the "for" loop (flag != 0), this will exit the for loop at first sign of a difference. You could put (arr1[i]==arr2[i]) in the condition for the for loop, but then you can't use the flag variable later as an indication of whether the two arrays were the same.