ArrayListType Max Value in Array

That's the problem

Add the function max, as an abstract function, to the class arrayListType to return the largest element of the list. Also, write the definition of the function max, in the class ArrayListType, and a program to test this function.

The problem is when I run this it returns 20, instead if the max randomly generated value anyone have any idea why?
Function within header File
1
2
3
4
5
6
7
8
9
10
11
template <class elemType>
int arrayListType<elemType>::max(int first, int last){
	int maxIndex;
	maxIndex = first;

	for(int loc = first +1; loc<=last; loc++)
		if(list[loc] < list[maxIndex])
			maxIndex = loc;
	return maxIndex;
}



implementation
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
#include <iostream>
#include "arrayListType.h"

using namespace std;

int main()

{
	int getMax;
	int counter;
	int number;

	arrayListType<int> intList(20);
	for(counter = 0; counter < 20; counter++)				//Line 7
    {	
		number = rand()%50; //Makes sure that the number is between 1 and 50	 				//Line 8
		intList.insertAt(counter, number);	
	}

	
	getMax = intList.max(0, 20);
	
	intList.print();
	cout<<getMax;


	system("PAUSE");

    }

_ When using random numbers you need to provide a seed (with srand()). Or the results will be always the same.
_ Your function is returning an index, not a value.
_ Probably you are accessing out of bounds, causing undefined behaviour. You insert 20 elements, so the last valid index in your array should be 19. (from 0 to n-1)
_ number = rand()%50; that's a number between 0 and 49.
_ system("PAUSE"); Don't do that. Refer to Console closing down and system is evil
Topic archived. No new replies allowed.