Arrays

I'm trying to create a function that determines the largest value in the array and then outputs the value and index. I want to values in the array to be random so I tried using the rand function, although I'm not sure where I'm supposed to put it. Any help would be greatly appreciated.

My main problem (I think) is outputting the correct values...

Thanks

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
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

void lastLargestIndex (int numbers[], int arraySize);                         


int main(int argc, char** argv) {
	
	int number, arraySize = 50;  
	
	int numbers[arraySize];                                                 
	for (int i = 0; i < arraySize; i++)
	{
		numbers[number] = (rand() + time(0) % 50);
	}
	lastLargestIndex(numbers, arraySize);
	
	return 0;
}

void lastLargestIndex (int numbers[], int arraySize)
{
	
	int largestNum = 0;

	for (int num = 1; num < arraySize; num++)
	{
		if (numbers[largestNum] < numbers[num])
		{
			largestNum = num;
		}
		
		
	}
	
	cout << "The largest number is: " << numbers[largestNum] << " ";
	
}
Last edited on
I made some corrections:

In line 17: number is used uninitialised. In fact number is completely redundant, so I got rid of it.

I added a call to srand to improve the randomness, otherwise you'll get the same results each time you run the program.

corrected the function lastLargestIndex which by the way is a confusing name (largest or last?)

Please observe very carefully the changes to that function.

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
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

void lastLargestIndex (int numbers[], int arraySize);                         


int main() 
{
	
	int arraySize = 50;  
	
	srand((unsigned int)time(0));
	
	int numbers[arraySize];                                                 
	for (int i = 0; i < arraySize; i++)
	{
		numbers[i] = (rand() + time(0) % 50);
	}
	lastLargestIndex(numbers, arraySize);
	
	return 0;
}

void lastLargestIndex (int numbers[], int arraySize)
{
	
	int largestNum = 0;
	int largestPos = 0;

	for (int num = 0; num < arraySize; num++)
	{
		if (largestNum < numbers[num])
		{
			largestNum = numbers[num];
			largestPos = num;
		}
	}
	
	cout << "The largest number is: " << largestNum << " at index: "  << largestPos << endl;
	
}
There also appears to be a problem here:
 
numbers[number] = (rand() + time(0) % 50);

This assigns a random number plus some value between 0 and 50. You can probably just use
 
numbers[number] = rand();

Topic archived. No new replies allowed.