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.
#include <iostream>
#include "limits.h"
usingnamespace 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;
}
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'
#include <iostream>
#include "limits.h"
usingnamespace 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;
}