How to find the two largest values of an array

I need to write a function that takes in an array of ints and its size and prints the two largest values from the array.
I am trying to figure out where I've messed up.

If I enter in the numbers "1 2 5 4 3", I get "5 2" as my output when it should be "5 4". If I enter in the numbers "10 12 14 8", it works correctly, outputting "14 12".

Here is what I have so far:

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
void printLargestTwo(int val[], int size){	
	int largest1 = val[0];
	int largest2 = val[1];
	int temp;
	
	if(largest2 > largest1) {
		temp = largest2;
		largest2 = largest1;
		largest1 = temp;
	}
	
	for(int i = 0; i < size; i++){
		if(val[i] > largest1){

			temp = largest1;
			largest1 = val[i];

			if(val[i] > largest2 && largest2 < largest1){
				largest2 = temp;				
			}			
		}
	}
	
	cout << largest1 << " " << largest2;
}
Last edited on
Right now, the if statements in the for loop are nested, so the second 'if' on line 18 doesn't get executed unless the first 'if' on line 13 was true. So if the number was less than the current highest, but greater than the current second highest, nothing changes.

Each time through the for loop, you're checking the new number against the ones you already have stored. You're only going to change the stored numbers if the new one is greater than the highest, or failing that, larger than the second highest. I think I would use an if, else if structure.

If the new number is higher than the highest of the two numbers (largest1), then the new number goes in largest1. The previous value of largest1 is now the second highest number and gets pushed down into largest2.

Else if the new number is greater than the second largest number, (largest2), then the new number is now the second highest number.

You've already sorted the first two numbers of the array, so I think you could start the for loop at i=2.
Last edited on
Topic archived. No new replies allowed.