Adam Hussein
Adam Hussein

Reputation: 75

Minimum of 10 numbers using for loop

I have a simple question in this code:

#include <iostream>
using namespace std;
int main () {
int x, mn = 10000;
for (int i = 0 ; i<10 ; i++)
{
     cin>>x;
    if (x<mn)
        mn=x;

}
cout << mn;
return 0;
} 

Why this outputs the minimum although if cases are true if we consider that the user won't enter a number greater than 10000?
My logic if the inputs are: in example 1, 2, 3, 4, 5, 6, 7, 8, 9, 10:

1<mn 
okay now mn =1; 
2<mn 
okay now mn =2; 
........ and so on, til mn = 10;

Why doesn't it output 10 (the last value)?
I will be thankful if you help.
PS: I also need a recommendation for better understanding how the code runs to me as a beginner.

Upvotes: 0

Views: 134

Answers (2)

Michael Dorgan
Michael Dorgan

Reputation: 12515

I have commented the code to help you understand each line.

#include <iostream>
using namespace std;
int main () {       // Start execution
int x, mn = 10000;  // Place a value of 10,000 into minimum - higher than the supposed maximum value that can be entered.  (This is not a good number to use)

for (int i = 0 ; i<10 ; i++)  // Loop 10 times
{
    cin>>x;    // Input a value into x
    if (x<mn)  // if x is less than mn (first loop it is 10,000) then...
        mn=x;  // Assign x into mn.

}
cout << mn;    // Output mn.  If no minimum was entered or found, this prints 10000
return 0;      // return 0
} 

Upvotes: 1

R Sahu
R Sahu

Reputation: 206577

Why doesn't it output 10 (the last value)?

Your understanding of the program is not correct.

You said:

1<mn 
okay now mn =1; 

That is correct.

2<mn 
okay now mn =2; 

That is not correct. At this time, value of mn is 1. Hence 2 < mn is not true. That would be true if you don't change of the value of mn but simply print x.

for (int i = 0 ; i<10 ; i++)
{
    cin>>x;
    if (x<mn)
      cout << x << endl;

}

Upvotes: 3

Related Questions