find maximum number in arrays

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
#include <iostream>
using namespace std;

int main()
{
	float array[20];
	float max=0;

	cout<<"Enter 20 numbers : "<<endl;
	for (int i=0; i<20; i++)
	{
		cout<<"Number : "<<1+i<<": ";
		cin>>array[i];
	}

	cout<<endl;

	for(int j = 0; j < 20; j++)
	{
		if(array[j] > max)
			{
				max=array[j];
			}
	}

	cout<<"\nLargest Number is :"<<max<<endl;

	system("PAUSE");
	return 0;
}	

Only problem I can see is if the user enters only negative numbers it will report the largest as being 0. If you instead initialize max to std::numeric_limits<float>::min() (smallest finite float value) you would not have this problem.
You can also initialize max to the first element of the array (after the user has inputted the numbers)
thx
Last edited on
1
2
3
4
5
6
            if (array[e]<array[r])
            {
                max=array[r];
                array[e]=array[r];
                max=array[e];
            }


Well, that's definitely wrong. Why would finding the max element require modifying the array? Why would you need to throw away the value of max immediately after assigning it? In addition max holds some unspecified value for an array of elements holding the same value. Why does the code only check 5 elements out of 100? Initializing array elements to some value may also be important if you wish to verify the code is correct by running it.
Topic archived. No new replies allowed.