1

I am new to c++ and I have been having a hard time understanding the following program. it looks so simple and so it made me feel like I am wrong about everything I have learn so far in c++.

    int number = 0;
    int min = 0; 

cout << "enter (-1) to stop" << endl;
while( number != -1)
{
    cout << "Enter an integer:";

    cin >> number ;
    if (number < min)
        min = number;
}
cout << "your minimum number is: " << min << endl;

what I am mostly confused about is the if statement. "min" has only been initialized as equal to zero so the entire if statement does not make sense to me. there is nothing that really defines "min" in the program in my opinion. Any contribution is much appreciated. thank you!

the program does work fine. And, indeed it does find the minimum of a set of numbers that a user enters. I just do not understand how that happens

3
  • 3
    Besides the initialization of min being flawed (it should be initialized to a very large number, typically std::numeric_limits<int>::max()), I'm not entirely sure what you mean. Can you please try to elaborate on the problem or your question? What do you mean with "there is nothing that really defines "min" in the program"? Commented Oct 23, 2018 at 6:50
  • 1
    The program (or at least this snippet) looks like it's finding out the smallest number of all the numbers you enter... and it works only for negative numbers anyway, because you have to stop it with -1, and that is also considered as one of the numbers. Commented Oct 23, 2018 at 6:52
  • 1
    This might also be a good time to learn how to debug your programs. Both using rubber duck debugging and an actual debugger to step through the code line by line is helpful in figuring out how the code works. Commented Oct 23, 2018 at 6:58

2 Answers 2

2

On each iteration of the loop a new number is read in using cin. Because number is a signed integer it is possible that it is less than min in which case the if will pass. It is strange that min starts at 0 but the if statement is not redundant.

Sign up to request clarification or add additional context in comments.

1 Comment

yes, it is quite strange to me as well I don't actually know if it is supposed to. Surprisingly though the program still works fine. But, thank you for the explanation
2

Initialize min with first number entered.

    cout << "enter (-1) to stop" << endl;

    cout << "Enter an integer:";
    cin >> number ;
    min = number;

    while( number != -1)
    {
        cout << "Enter an integer:";
        cin >> number ;
        if (number < min)
            min = number;      
   }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.