Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Conditional Incrementing Incorrectly

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading