Why does my program not increment count whenever there is a negative number?

Viewed 68
#include <iostream>
using namespace std;

int main()
{
    const int MAX = 10; // max loops
    int count = 0; // count for the while loop
    int smallest; // output
    int largest = 0; // output
    int input; // stores each number read

    cout << "Enter 10 integers => ";

    while(count < MAX)
    {
    
        cin >> input;

        if(input >= largest)
        {
            largest = input;
            ++count;
        }

        if(input <= smallest)
        {
        smallest = input;
        ++count;
        }
        if(input < largest and input > smallest)
        {
            ++count;
        }
    
    }

     cout << "The largest is: " << largest << endl;
     cout << "The smallest is: " << smallest << endl;
    return 0;
}

My program does not increment count whenever there is a negative number.

Negative integer test case works with 11 integers but not with 10

Works with positive numbers

2 Answers

Always initialize your variables before using them in your program. The value of uninitialized memory could be anything. Here the value of the variable 'input' could be initialized with a value that might give you an incorrect result. Sometimes it may give correct results, it also may not. The bottom line is to always initialize variables. As people have pointed out in the comments, a debugger (VSCode) for instance might actually tell you actual evidence as to how an uninitialized memory can return erroneous values.

You should initialize smallest with the first input you have, and then compare the rest of your inputs compared to that. Since it's not initialized with a value, it can contain any number that int allows.

In the while loop;

while (count < MAX) {
    cin >> input;
    if (!count) { // If count equals to zero
        smallest = input;
    }

}
Related