Finding a minimum value in a for-loop and keeping the index of it

I am working a problem where I calculate the values in an interval of integers of a function (f(x) = x * x – 12 * x + 40) in a 'for' loop. I need to find a minimum value. That's all fine, but I also need to keep the index number for which the value was smallest. At the moment I reiterate the function again in another loop, but this does not look like a good way. Do you have any tips for me? Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include "limits.h"
using namespace std;

int main ()
{
    int lBound, uBound, y, min;
    
    cout << "Give the lower and the upper bounds of integer numbers: " << endl;
    cin >> lBound >> uBound;
    
    
    min=INT_MAX;
    int x = lBound;
    for (int i = x; i <=uBound; i ++) {
        y = i * i - 12 * i + 40;
        cout << x << " " << y << endl;
        if (y<min) {
            min=y;
        }
        x++;
        
    }
    for (int i = lBound; i <= uBound; i++) {
        y = lBound * lBound - 12 * lBound + 40;
        if (y==min) {
            y = lBound;
            break; // terminates the loop
        }
        lBound++;
    }
    
    
    cout << "smallest value of the function is " << min << " for x = " <<  y << endl;
    
    
    return 0;
}
Last edited on
Your loops are obfuscated.
You've got all the info needed in the 'i' variable, there is no need for 'x' or to touch 'lBound'.
Also it's confusing that 'y' changes its meaning from f(x) to 'x'

1
2
3
4
5
        y = f(x);
        if (y<min) {
            min=y;
            x_min=x; 
        }
thanks a lot I can't believe I could not see such an obvious solution.

here is the correction. If there are other mistakes, I will appreciate if you point them to me.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include "limits.h"

using namespace std;

int main ()
{
    int lBound, uBound, y, min, x_min;
    
    cout << "Give the lower and the upper bounds of integer numbers: " << endl;
    cin >> lBound >> uBound;
    
    
    min=INT_MAX;
    for (int i = lBound; i <=uBound; i ++) {
        y = i * i - 12 * i + 40;
        if (y<min) {
            min=y;
            x_min = i;
        }
    }
        
    
    cout << "smallest value of the function is " << min << " for x = " <<  x_min << endl;
    
    
    return 0;
}
It's pretty charming when wearing [url=http://www.cwmalls.com/women-true-full-grain-cow-leather-elegant-open-toe-platform-thick-heel-shoes-dress-sandals-orange]leather high heel dress shoes[/url] and this is the best choice.
Topic archived. No new replies allowed.