Ok, here are some immediate errors or ambiguities that I see:
1. In the FOR loop, the variable index1 has a range of 0->elements-1 inclusive. However, the segmentation fault (index array out of bounds) error would probably occur at lines 7, 9, and 11 (if the variable elements is the size of the array a) because you try to access a[index1+1] when this area in memory is not allocated. You are essentially accessing one past the last valid element in array a.
FIX: You could alter the FOR loop construct to look like
for (unsigned index1 = 0; index1 < elements-1; index1++)
2. You increment count each time a[index1] == a[index1+1]. In this algorithm, you only want to increment count when the data changes from increasing to decreasing or decreasing to increasing. When two contiguous elements are equal, there is technically no change in data direction. You did a good job of breaking the algorithm down into individual cases, however the logic is not yet complete.
The first case is the data was previously increasing, but it has changed direction and is now decreasing.
1 2 3 4 5
|
if (a[index1] > a[index1+1] && direction == "increasing")
{
count++;
direction = "decreasing";
}
| |
The second case is the data was previously decreasing, but it has changed direction and is now increasing.
1 2 3 4 5
|
if (a[index1] < a[index1+1] && direction == "decreasing")
{
count++;
direction = "increasing";
}
| |
The third case is the data is neither increasing or decreasing.
1 2
|
if (a[index1] == a[index1+1])
//Do nothing!
| |
So you see, a key component you were missing was storing a direction variable and testing it in the IF statements.
There is another technicality to this problem and it concerns inputs where the first two or more elements are equal e.g. {5, 5, 5, 7, 9, 3, 2} because you must first initialize a direction (increasing or decreasing). There is a simple workaround of iterating until two elements are not equal and then initialize the direction variable and begin the algorithm. I have a correct algorithm implemented, however, I will let this all sink in before posting it. Its important to understand the idea like you said!