Find the two largest numbers in an array

Find two largest elements array

Given an array of positive integers. Find the first and second largest elements in the array.

Largest two numbers in an array solution

One solution is to use two loops. The first loop finds the first maximum and the second loop finds the second maximum. Note that the second loop needs to exclude the first maximum. In the next post we will solve this problem using only a single loop.

Code

Here is a c program to print largest two numbers using two loops

//Includes
#include <iostream>

//Name space
using namespace std;

//Main function
void main()
{
	//Array
	int A[10] = {5, 1, 2, 3, 4};

	//Array size
	int n = 5;

	//First maximum
	int max1 = -1;

	//Find the first maximum
	for (int i = 0; i < n; i++)
	{
		if (A[i] > max1)
		{
			max1 = A[i];
		}
	}

	//Second maximum
	int max2 = -1;

	//Find the second maximum excluding
	//the first maximum
	for (int i = 0; i < n; i++)
	{
		if (A[i] != max1 && A[i] > max2)
		{
			max2 = A[i];
		}
	}

	//Print out
	cout << "max1 = " << max1 << endl;
	cout << "max2 = " << max2 << endl;
}

Please use the comments section below for questions or feedback. Thanks for visiting.

Tags:

Leave a Reply