array question
Hi Guru's
I wrote a program to return the max value from an array using a "for" loop in my function
but Im having trouble with the logic when rewriting the function using a "while" loop.
If someone would be so kind in showing me where I went wrong I would greatly appreciate it.
Thanks,
trip7
#include <iostream.h>
#include <conio.h>
#include <iomanip.h>
double find_max(int []);
main()
{
int num[10]={10,20,30,40,50,60,70,80,90,100};
cout <<"Original numbers are ";
int i=0;
while(i<10)
{
cout <<num[i] <<" ";
i++;
}
cout <<"\n\n Max value = " <<find_max(num);
return 0;
}
//function to compute max values
double find_max(int vals[10])
{
int i=0, max=vals[0];
while(i<10)
{
if(max<vals[i])
{
max=vals[i];
i++;
}
}
return max;
}
[1007 byte] By [
trip7] at [2007-11-18 18:23:22]

# 2 Re: array question
Actually the most obvious thing is the placement of your i++; in your increment.
You see right now your code says "only increment i if max < vals[i]" and it will NEVER happen because you first initialize it to the first item in your list, let's say 5. And your first comparison is against teh first element, so you have "if 5 is less than 5, set the new max and increment"
In short terms: move your i++; to OUTSIDE that if statement and put it as the last line of your while loop
# 3 Re: array question
What's the problem that you are seeing?
Also, then correct usage for main is
int main( ... )
not
main( ... )
Also, use the new iostream header - no ".h"
#include <iostream>
#include <iomanip>
# 4 Re: array question
You are only incrementing the counter when you find a new max, it needs to be incremented every time through the loop:
//function to compute max values
double find_max(int vals[10])
{
int i=0, max=vals[0];
while(i<10)
{
if(max<vals[i])
{
max=vals[i];
}
i++;
}
return max;
}
# 7 Re: array question
Originally posted by trip7
Did I use the rating properly?
Nobody cares about the ratings and most people don't use them, so don't worry about it.
# 8 Re: array question
Yeah but I wish people _did_ use the rating. It's a trend I've been trying to start for like 2 years now :)
Basically if you rate the thread, you know it's complete so you don't have to click on it to see if further explanation is wanted. I think it's helpful -- not so much the value of the rating, just the fact that it's there.