0

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.

Adam Hussein
  • 75
  • 5
  • 12

2 Answers2

3

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;

}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Thank you, that went so far to my mind, I don't expect that the value gonna change from 10000 to 1. That's what I don't understand. – Adam Hussein Jan 12 '18 at 21:38
  • @AdamHussein, the line `mn = x;` changes the value of `mn`. – R Sahu Jan 12 '18 at 21:39
  • Got it, he was not able to mentally trace execution the second time through when mn was already equal to 1. A debugger really helps with this. – Michael Dorgan Jan 12 '18 at 21:40
1

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
} 
R Sahu
  • 204,454
  • 14
  • 159
  • 270
Michael Dorgan
  • 12,453
  • 3
  • 31
  • 61