coolcode
coolcode

Reputation: 31

program to find the minimum of a set of numbers using while loop in c++

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

Upvotes: 1

Views: 6473

Answers (2)

kiran Biradar
kiran Biradar

Reputation: 12742

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;      
   }

Upvotes: 2

Khan Maxfield
Khan Maxfield

Reputation: 399

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.

Upvotes: 2

Related Questions