Home > OS >  Conditional Incrementing Incorrectly
Conditional Incrementing Incorrectly

Time:02-24

My function

int numSteepSegments(const int heights[], int arrSize) {

    int mile = 0, steep_count = 0;

    while (mile <= arrSize) {
        int height = heights[mile];
        int height_next = heights[mile   1];
        if ((height   1000) < height_next) {
              steep_count;
        } else if ((height - 1000) > height_next) {
              steep_count;
        }
        cout << heights[mile] << endl;
        cout << steep_count << endl;

          mile;
    }
    return steep_count;
}

is spitting out twice as many steep_count than it is supposed to.

With the array: 1200, 1650, 3450, 2800, 2900, 1650, 1140, 1650, 1200, and the arrSize = 9, what am I missing?

the cout's are:

1200
0
1650
1
3450
1
2800
1
2900
2
1650
2
1140
2
1650
2
1200
3
1746942513
4

What is that last value? It's obviously not in the array, and I can't see it belonging anywhere near the numbers I'm dealing with. What am I not seeing in my conditionals that's causing the wrong increments to steep_count?

CodePudding user response:

C/C arrays are zero-based. The indices for an array with arrSize elements range from 0 to arrSize-1.

Your loop index mile ranges from 0 to arrSize (inclusive), so heights[mile] is walking off the end of the array. Also, you are indexing heights[mile 1] which would exceed the array limits even if your index were limited to arrSize-1.

Try either:

  • changing your loop to range from 0 to arrSize-2 (inclusive), or
  • changing your loop to range from 1 to arrSize-1 and use mile-1 for the first index.
  • Related