### Thread: Error in Obtaining Minimum Value in my C++/CLI program

1. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Aug 2013
Posts
232
Rep Power
5

#### Error in Obtaining Minimum Value in my C++/CLI program

Hello,

So I followed another example out of the Ivor Horton book, and its pretty much modeled after a similar example that he did on obtaining random numbers in a C++/CLI program.

The only difference is that before, he obtained the max in the previous example, and now I have to find the minimum value.

Basically this program creates a double array and fills it with random numbers that I later print the values of, and then I will determine the minimum with a for loop as well as an embedded for loop that will examine each element of the array.

The issue I'm having is with the logic of determining the minimum of the array, and assigning that value to a variable.

Here is the author's logic on how he obtained the maximum at the very end of the previous example:

Code:
```if(max < sample)
max = sample;```
For some reason, I thought, Hmm, since I'm determining the minimum, let me flip the logic to obtain the minimum.

It's only giving me the very last element of the loop, so it makes me think that it's assigning EVERY element to the minimum variable I declared.

Should I put an if statement to prevent this and to check upon the current "minimum" value?

Here's my code with the similar statement in bold, let me know what you think, thanks a bunch for reading my post!:

Code:
```// Chapt4_Exercise4.cpp : main project file.

#include "stdafx.h"

using namespace System;

int main(array<System::String ^> ^args)
{

/* 4. Write a C++/CLI program that creates an array with a random number of elements of
type int.

The array should have from 10 to 20 elements.

Set the array elements to random values between 100 and 1000.

Output the elements five to a line in ascending sequence without sorting the array;
for example find the smallest element and output that, then the next smallest, and so on.

*/

// Create a double array:

array<double>^ random_array = gcnew array<double>(50);

// gcnew is used to specify objects that are created and are
// automatically garbage-collected

// Make a random number generator to use to fill in values for the array:

Random^ random_num_generator = gcnew Random;

// Make a for loop that will go along the length of the random_num array:

for(int i = 0; i < random_array->Length; i++)
{

random_array[i] = 100.0*random_num_generator->NextDouble();

}

Console::WriteLine(L"Here is what is actually inside the random array: \n\n\n");

// Make a for loop to output each individual element of the random_array:

for(int i = 0; i < random_array->Length; i++)
{

Console::Write(L"{0,10:F2}", random_array[i]);

if((i+1)% 5 == 0)
{
Console::WriteLine();
}

}

// Find the minimum value

// I tried making the logic to find the maximum value to be just the opposite
// so that I could find the minimum, work on this logic!

double min;

// I initialized this double variable named minimum to be equal to zero at first
// but it's still assigning it to zero (obviously because its the default
// value for null when you initialize a variable in C++)

for each(double value in random_array)
{

// This is a for loop that will look through each double value within the
// random_array that I created above

// Maybe assign the minimum to the first element of the array just
// for giggles to make it relevant

for(int i = 0; i < random_array->Length; i++)
{

// This is another for loop that will go along the length of the random
// array

min = random_array[i];

// This will assign the minimum to be the first element of the array
// so it isn't no longer equal to zero like before without this embedded
// for loop

// The problem now is that the last element of the loop is now the minimum
// which is obviously not the minimum value whatsoever

// FIX THIS

if(min < value)
{

// This is an if statement that will check to see if minimum is less than
// the current value aka element that's being examined, then
// make it the new minimum

// The problem is, that once minimum is initialized above, none of the
// numbers that follow it will cause minimum to be changed

// I need to make the minimum variable reflect the current minimum
// number, but also keep comparing it to the overall array to keep it
// current

// This logic is flawed

min = value;
}
}

}

Console::WriteLine(L"The minimum value in the array is {0:F2}", min);

return 0;
}```
Last edited by HauntJemimah; October 11th, 2013 at 11:04 AM.
2. Consider this general approach to such a problem:
You want min to contain the minimum value encountered. Therefore, if the value you're testing is less than the current value of min, then you want save that value in min. Another way to express that is that if min is greater than value then you want to save value in min.

What about the first test? That would depend on what value you initialized min to be. Since you want to save the first value, you need to initialize min to be greater than the first value, regardless of what that first value is. You could use a kludge (eg, have a "first_time" flag that would by-pass the test the first time and arbitrarily do the deed), but far more elegant would be to initialize min to the largest possible value. You will find macros for the maximum and minimum possible values of the built-in datatypes in the limits.h header file.

And min should only be used to hold the minimum value. Seems obvious, but ... .

Code:
```    double min;
// You haven't initialized min, so it contains random garbage.

for each(double value in random_array)
{
// I do not understand what this inner for-loop is for.
// The for-each iterates through every value in the array, just as
//      the for-loop does, so why duplicate the effort?
for(int i = 0; i < random_array->Length; i++)
{
min = random_array[i];
// Why did you just change the value of min?
// You just threw away the previously found minimum value
//   (assuming that your test for the minumum worked, which it doesn't).

// Verify your logic here.  Aren't you instead saving the maximum value?
if(min < value)
{
min = value;
}
}
}```
3. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Aug 2013
Posts
232
Rep Power
5
Originally Posted by dwise1_aol
Consider this general approach to such a problem:
You want min to contain the minimum value encountered. Therefore, if the value you're testing is less than the current value of min, then you want save that value in min. Another way to express that is that if min is greater than value then you want to save value in min.

What about the first test? That would depend on what value you initialized min to be. Since you want to save the first value, you need to initialize min to be greater than the first value, regardless of what that first value is. You could use a kludge (eg, have a "first_time" flag that would by-pass the test the first time and arbitrarily do the deed), but far more elegant would be to initialize min to the largest possible value. You will find macros for the maximum and minimum possible values of the built-in datatypes in the limits.h header file.

And min should only be used to hold the minimum value. Seems obvious, but ... .

Code:
```    double min;
// You haven't initialized min, so it contains random garbage.

for each(double value in random_array)
{
// I do not understand what this inner for-loop is for.
// The for-each iterates through every value in the array, just as
//      the for-loop does, so why duplicate the effort?
for(int i = 0; i < random_array->Length; i++)
{
min = random_array[i];
// Why did you just change the value of min?
// You just threw away the previously found minimum value
//   (assuming that your test for the minumum worked, which it doesn't).

// Verify your logic here.  Aren't you instead saving the maximum value?
if(min < value)
{
min = value;
}
}
}```
I removed the embedded for loop, and changed the sign at the very end so it would reflect the instance you mentioned in which, if the saved minimum value is GREATER than the current value, then it would change the minimum to be equal to that current value.

I know that the limits for the max and min values lie within the limits.h library, but how do I necessarily implement the "minimum" possible value in this program.

Anyway, I tried to make the revisions you suggested.

Hopefully, my logic makes sense, let me know.

Here's my code:

Code:
```// Chapt4_Exercise4.cpp : main project file.

#include "stdafx.h"

using namespace System;

int main(array<System::String ^> ^args)
{

/* 4. Write a C++/CLI program that creates an array with a random number of elements of
type int.

The array should have from 10 to 20 elements.

Set the array elements to random values between 100 and 1000.

Output the elements five to a line in ascending sequence without sorting the array;
for example find the smallest element and output that, then the next smallest, and so on.

*/

// Create a double array:

array<double>^ random_array = gcnew array<double>(50);

// gcnew is used to specify objects that are created and are
// automatically garbage-collected

// Make a random number generator to use to fill in values for the array:

Random^ random_num_generator = gcnew Random;

// Make a for loop that will go along the length of the random_num array:

for(int i = 0; i < random_array->Length; i++)
{

random_array[i] = 100.0*random_num_generator->NextDouble();

}

Console::WriteLine(L"Here is what is actually inside the random array: \n\n\n");

// Make a for loop to output each individual element of the random_array:

for(int i = 0; i < random_array->Length; i++)
{

Console::Write(L"{0,10:F2}", random_array[i]);

if((i+1)% 5 == 0)
{
Console::WriteLine();
}

}

// Find the minimum value

// I tried making the logic to find the maximum value to be just the opposite
// so that I could find the minimum, work on this logic!

double min;

// I initialized this double variable named minimum to be equal to zero at first
// but it's still assigning it to zero (obviously because its the default
// value for null when you initialize a variable in C++)

for each(double value in random_array)
{

if(min > value)
{

// This is an if statement that will check to see if minimum is less than
// the current value aka element that's being examined, then
// make it the new minimum

// The problem is, that once minimum is initialized above, none of the
// numbers that follow it will cause minimum to be changed

// I need to make the minimum variable reflect the current minimum
// number, but also keep comparing it to the overall array to keep it
// current

// This logic is flawed

min = value;
}
}

Console::WriteLine(L"The minimum value in the array is {0:F2}", min);

return 0;
}```
4. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Aug 2013
Posts
232
Rep Power
5
I went through each line and tried to decipher it like a language like you said (much like how Larry Wall interprets Perl for example), and I understood it better.

After thinking about it for a bit, I thought maybe a quick fix would be just to make minimum equal to some arbitrary value, like 5.

The program works, but every once in a while, the only minimum found would actually be 5, which is obviously false, therefore my logic is flawed yet again.

I also took out the for each loop, and made a regular for loop, because for some reason it made sense to me to utilize an integer variable i so that I could change the current minimum of the array at will.

But then again, I could be wrong so heh, I don't know honestly.

Anyway, here is my code thus far:

// Chapt4_Exercise4.cpp : main project file.

#include "stdafx.h"

using namespace System;

int main(array<System::String ^> ^args)
{

/* 4. Write a C++/CLI program that creates an array with a random number of elements of
type int.

The array should have from 10 to 20 elements.

Set the array elements to random values between 100 and 1000.

Output the elements five to a line in ascending sequence without sorting the array;
for example find the smallest element and output that, then the next smallest, and so on.
Code:
```*/

// Create a double array:

array<double>^ random_array = gcnew array<double>(50);

// gcnew is used to specify objects that are created and are
// automatically garbage-collected

// Make a random number generator to use to fill in values for the array:

Random^ random_num_generator = gcnew Random;

// Make a for loop that will go along the length of the random_num array:

for(int i = 0; i < random_array->Length; i++)
{

random_array[i] = 100.0*random_num_generator->NextDouble();

}

Console::WriteLine(L"Here is what is actually inside the random array: \n\n\n");

// Make a for loop to output each individual element of the random_array:

for(int i = 0; i < random_array->Length; i++)
{

Console::Write(L"{0,10:F2}", random_array[i]);

// This is an if loop that will occur for every fifth element of the
// array:

if((i+1)% 5 == 0)
{
Console::WriteLine();
}

}

// Find the minimum value

// I tried making the logic to find the maximum value to be just the opposite
// so that I could find the minimum, work on this logic!

double min = 5;

// I initialized this double variable named minimum to be equal to zero at first
// but it's still assigning it to zero (obviously because its the default
// value for null when you initialize a variable in C++)

// Old for each loop that is commented out to try a new idea:
// for each(double value in random_array)

for (int i = 0; i < random_array->Length; i++)
{
// Since minimum equals 0 or null by default, the number ZERO will NEVER
// be greater than the current value

// Maybe let's just assign minimum to be equal to the current element
// of the random_array

// I don't understand the behavior of this loop, I'm telling the program
// to start at the first elemetn of the random_array, go along its entire
// length, and go through each element one at a time.

// Then I assign the minimum to the current element of random_array

// THE MAIN PROBLEM IS IN THE FOLLOWING STATEMENT:

// min = random_array[i];

// How am I going to assign a random value that would exist

// If that known element is greater

if(min > random_array[i])
{

// This is an if statement that will check to see if minimum is less than
// the current value aka element that's being examined, then
// make it the new minimum

// The problem is, that once minimum is initialized above, none of the
// numbers that follow it will cause minimum to be changed

// I need to make the minimum variable reflect the current minimum
// number, but also keep comparing it to the overall array to keep it
// current

min = random_array[i];
}
}

Console::WriteLine(L"The minimum value in the array is {0:F2}", min);

return 0;
}```
5. Originally Posted by HauntJemimah
I went through each line and tried to decipher it like a language like you said (much like how Larry Wall interprets Perl for example), and I understood it better.
I offerred that autobiographical bit for two reasons, one of which you did take up:

1. Reading and writing code with an understanding of what you are actually telling the compiler is an important skill to develop. As with everything you write, even the stuff written in human languages.

2. That viewpoint informs my own approach to somebody else's code, especially on this forum. I will approach an erroneous statement (eg, trying to add a letter value to a char array name) and I will tell the person what that he is actually saying there. Then I will offer that if he instead meant something else (which is obviously what he had intended instead), then here is how he should say that. It would be like someone saying in German, "Ich bin kalt." ("I'm cold.") and, after all German speakers around him had finished looking at him very funny (less funny now with all the zombie movies), I would point out that he just said that he's dead, but if he wanted to say that he felt cold then that would be, "Es ist mir kalt." ("It's cold to me.")

Originally Posted by HauntJemimah
After thinking about it for a bit, I thought maybe a quick fix would be just to make minimum equal to some arbitrary value, like 5.

The program works, but every once in a while, the only minimum found would actually be 5, which is obviously false, therefore my logic is flawed yet again.
Yes, initializing min is what I wanted you to do. Initializing it to 5 is one choice, but as you have found yourself that choice doesn't always work.

In order to have the first value in the array assigned to min, that first value must be less than the initial value in min. Which means that the initial value of min must be greater than any possible value in that array.

If 5 would sometimes work, what about a larger value, like 42? Or 100? Or 1000? Or 1000000? Or, dare I even suggest it, the largest possible value that a double variable could possibly hold?

How are we to know what that largest possible double value is? A simple way would be look up the header files. Now, I knew that the min and max limits of datatypes were contained in limits.h, which is why I recommended it to you. I just now looked there and in MinGW gcc discovered that the limits for neither float nor double are to be found there. I did see another header file, float.h, in which I found the limits for both floats and doubles. From MinGW gcc's float.h:
Code:
```/* The number of base FLT_RADIX digits in the mantissa. */
#define FLT_MANT_DIG	24

/* The maximum floating point number. */
#define FLT_MAX		3.40282347e+38F

/* Maximum n such that FLT_RADIX^n - 1 is representable. */
#define FLT_MAX_EXP	128

/* Maximum n such that 10^n is representable. */
#define FLT_MAX_10_EXP	38

/* Minimum normalized floating-point number. */
#define FLT_MIN		1.17549435e-38F

/* Minimum n such that FLT_RADIX^n is a normalized number. */
#define FLT_MIN_EXP	(-125)

/* Minimum n such that 10^n is a normalized number. */
#define FLT_MIN_10_EXP	(-37)

/*
* The characteristics of double.
*/
#define DBL_DIG		15
#define DBL_EPSILON	1.1102230246251568e-16
#define DBL_MANT_DIG	53
#define DBL_MAX		1.7976931348623157e+308
#define DBL_MAX_EXP	1024
#define DBL_MAX_10_EXP	308
#define DBL_MIN		2.2250738585072014e-308
#define DBL_MIN_EXP	(-1021)
#define DBL_MIN_10_EXP	(-307)```
Therefore, I personally would choose to use DBL_MAX.

I wasn't feeling well yesterday, extremely tired and needing to sleep as I have felt before with high fevers, though this time with no fever. I'm seeing if I feel better today.

So when I encountered your question of how to use limits.h, I couldn't understand what part you didn't understand. Perhaps it was what I had just discovered myself, that the macro definitions were instead in float.h. Or, because C++ instruction is intended to lead you away from using macros, replacing them with const declarations, I thought that maybe you just weren't at all familiar with macros (AKA "#defines"). I'll bypass those questions now by saying that you use the macro name in the place of the value, such that min's declaration would be:
Code:
`    double min = DBL_MAX;`
Though you would, of course, need to #include float.h.
6. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Aug 2013
Posts
232
Rep Power
5
Originally Posted by dwise1_aol
I offerred that autobiographical bit for two reasons, one of which you did take up:

1. Reading and writing code with an understanding of what you are actually telling the compiler is an important skill to develop. As with everything you write, even the stuff written in human languages.

2. That viewpoint informs my own approach to somebody else's code, especially on this forum. I will approach an erroneous statement (eg, trying to add a letter value to a char array name) and I will tell the person what that he is actually saying there. Then I will offer that if he instead meant something else (which is obviously what he had intended instead), then here is how he should say that. It would be like someone saying in German, "Ich bin kalt." ("I'm cold.") and, after all German speakers around him had finished looking at him very funny (less funny now with all the zombie movies), I would point out that he just said that he's dead, but if he wanted to say that he felt cold then that would be, "Es ist mir kalt." ("It's cold to me.")

Yes, initializing min is what I wanted you to do. Initializing it to 5 is one choice, but as you have found yourself that choice doesn't always work.

In order to have the first value in the array assigned to min, that first value must be less than the initial value in min. Which means that the initial value of min must be greater than any possible value in that array.

If 5 would sometimes work, what about a larger value, like 42? Or 100? Or 1000? Or 1000000? Or, dare I even suggest it, the largest possible value that a double variable could possibly hold?

How are we to know what that largest possible double value is? A simple way would be look up the header files. Now, I knew that the min and max limits of datatypes were contained in limits.h, which is why I recommended it to you. I just now looked there and in MinGW gcc discovered that the limits for neither float nor double are to be found there. I did see another header file, float.h, in which I found the limits for both floats and doubles. From MinGW gcc's float.h:
Code:
```/* The number of base FLT_RADIX digits in the mantissa. */
#define FLT_MANT_DIG	24

/* The maximum floating point number. */
#define FLT_MAX		3.40282347e+38F

/* Maximum n such that FLT_RADIX^n - 1 is representable. */
#define FLT_MAX_EXP	128

/* Maximum n such that 10^n is representable. */
#define FLT_MAX_10_EXP	38

/* Minimum normalized floating-point number. */
#define FLT_MIN		1.17549435e-38F

/* Minimum n such that FLT_RADIX^n is a normalized number. */
#define FLT_MIN_EXP	(-125)

/* Minimum n such that 10^n is a normalized number. */
#define FLT_MIN_10_EXP	(-37)

/*
* The characteristics of double.
*/
#define DBL_DIG		15
#define DBL_EPSILON	1.1102230246251568e-16
#define DBL_MANT_DIG	53
#define DBL_MAX		1.7976931348623157e+308
#define DBL_MAX_EXP	1024
#define DBL_MAX_10_EXP	308
#define DBL_MIN		2.2250738585072014e-308
#define DBL_MIN_EXP	(-1021)
#define DBL_MIN_10_EXP	(-307)```
Therefore, I personally would choose to use DBL_MAX.

I wasn't feeling well yesterday, extremely tired and needing to sleep as I have felt before with high fevers, though this time with no fever. I'm seeing if I feel better today.

So when I encountered your question of how to use limits.h, I couldn't understand what part you didn't understand. Perhaps it was what I had just discovered myself, that the macro definitions were instead in float.h. Or, because C++ instruction is intended to lead you away from using macros, replacing them with const declarations, I thought that maybe you just weren't at all familiar with macros (AKA "#defines"). I'll bypass those questions now by saying that you use the macro name in the place of the value, such that min's declaration would be:
Code:
`    double min = DBL_MAX;`
Though you would, of course, need to #include float.h.
Haha, cool note about the German language. What a cool way of looking at it, I dig it. Plus some of those German zombie movies are awesome, (Dead Snow!!! :D)

I hope you get better! Being sick always sucks, believe me, I always get spontaneous colds more than anyone so I know how it feels. But regardless, don't respond to my posts if you really need to rest haha.

Anyway, so I included the limit.h file like you suggested, and it works! :)

The limits.h file wasn't too hard to understand either, made sense too that someone would openly define a maximum value.

Very cool, either way, thanks a bunch for always putting up with my examples, I really want to get better since I know I have more sense of just math and the whole logic behind the programming process than I ever did in High School.

I really would like to maybe apply this in Clinical Research with the scripting languages (though, I still need to get the Clinical Research Assistant job first, been applying like crazy and haven't got a break yet, ugh... sometimes I really hate where my life has been going heh)

Either way, its very motivating that you guys have helped me so far, so thanks a bunch.

Here's my final code:
Code:
```// Chapt4_Exercise4.cpp : main project file.

#include "stdafx.h"
#include "float.h"

using namespace System;

int main(array<System::String ^> ^args)
{

/* 4. Write a C++/CLI program that creates an array with a random number of elements of
type int.

The array should have from 10 to 20 elements.

Set the array elements to random values between 100 and 1000.

Output the elements five to a line in ascending sequence without sorting the array;
for example find the smallest element and output that, then the next smallest, and so on.

*/

// Create a double array:

array<double>^ random_array = gcnew array<double>(50);

// gcnew is used to specify objects that are created and are
// automatically garbage-collected

// Make a random number generator to use to fill in values for the array:

Random^ random_num_generator = gcnew Random;

// Make a for loop that will go along the length of the random_num array:

for(int i = 0; i < random_array->Length; i++)
{

random_array[i] = 100.0*random_num_generator->NextDouble();

}

Console::WriteLine(L"Here is what is actually inside the random array: \n\n\n");

// Make a for loop to output each individual element of the random_array:

for(int i = 0; i < random_array->Length; i++)
{

Console::Write(L"{0,10:F2}", random_array[i]);

// This is an if loop that will occur for every fifth element of the
// array:

if((i+1)% 5 == 0)
{
Console::WriteLine();
}

}

// Find the minimum value

// I tried making the logic to find the maximum value to be just the opposite
// so that I could find the minimum, work on this logic!

double min = DBL_MAX;

// I initialized this double variable named minimum to be equal to zero at first
// but it's still assigning it to zero (obviously because its the default
// value for null when you initialize a variable in C++)

// Old for each loop that is commented out to try a new idea:
// for each(double value in random_array)

for (int i = 0; i < random_array->Length; i++)
{
// Since minimum equals 0 or null by default, the number ZERO will NEVER
// be greater than the current value

// Maybe let's just assign minimum to be equal to the current element
// of the random_array

// I don't understand the behavior of this loop, I'm telling the program
// to start at the first elemetn of the random_array, go along its entire
// length, and go through each element one at a time.

// Then I assign the minimum to the current element of random_array

// THE MAIN PROBLEM IS IN THE FOLLOWING STATEMENT:

// min = random_array[i];

// How am I going to assign a random value that would exist

// If that known element is greater

if(min > random_array[i])
{

min = random_array[i];
}
}

Console::WriteLine(L"The minimum value in the array is {0:F2}", min);

return 0;
}```