c++ Find the smallest number

Asked 2 years ago, Updated 2 years ago, 108 views


    int i, min = 0;
    for (i = 0; i < 10; i++)
    {
        cin >> number;
        if (i == 0)              // Condition A
            min = number;
        else if (min > number)   // Condition B
            min = number;
    }
    cout << min;

Hello, the above source code is the code that can find the smallest number among the numbers received as input. Why is if(i==0) a conditional statement for finding the smallest number? Isn't i==0 the first number you entered? I'm a beginner in coding, so I don't understand well. Please explain.

c++ for if문

2022-09-20 19:55

1 Answers

It is a code that compares min and input values while going around the repetition door to store the smallest number in min.

What value does the min need to have for comparison?

So, at the beginning of a repeating sentence, the input value is substituted into min without comparing it (if(i==0) min=number;), and then compared to min from the repetition, and stored in min if the input value is less than min.

Eventually, the smallest value of the number entered is stored. Even if the iteration is one time, the smallest value will be stored by the substitution.


2022-09-20 19:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.