Reputation: 4679
I am working on a homework assignment 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 looks really messy. Also I could derive x and calculate the answer using the known minimum, but that's also weird, because derivation is not so straightforward. Do you have any tips for me? Thanks.
#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;
i=uBound; // terminates the loop
}
lBound++;
}
cout << "smallest value of the function is " << min << " for x = " << y << endl;
return 0;
}
Upvotes: 0
Views: 3020
Reputation: 137930
i=uBound; // terminates the loop
This is not a very good coding practice. To terminate a loop, you should use a flow control construct like break
. Doing so in this case would preserve the index of the minimum element.
Edit: If you want i
to outlive the loop, you simply need to declare it outside. To wit:
change
for (int i = lBound; i <= uBound; i++) {
to
int i; // variable exists outside loop
for (i = lBound; i <= uBound; i++) {
Furthermore, just FYI, loop bounds are usually specified as half-open intervals to avoid the potential issue where lbound
and ubound
represent the limits of the int
data type. This means that you usually use <
instead of <=
.
It's not clear if you're in an algebra class or a CS class…
Upvotes: 1
Reputation: 42825
Here's a hint: Whenever you need to "keep something around" in a program, that means you need to store it in a variable. Whether that variable is local, global, or passed around depends on how long you need to keep it around. This is called the variable's "scope". It's considered good practice to keep the scope of any variable to a minimum, hence the guidelines discouraging globals.
Upvotes: 3