C++ program to find the largest and second largest number present in an array

C++ program to find the largest and second-largest numbers present in an array along with their location index on the array. This program first find the largest number by going through all the numbers in the array. It stores the index of the largest number on the variable pos1 and largest number is the largest variable. A second for loop is applied, which also check for the largest number. When it hits on the largest found by the first loop, it is bypassed using a continue statement and hence will get the second-largest number.

#include <iostream>
#include <conio.h>
using namespace std;

void main()
{
	int a[10], i, largest = 0, second_largest = 0, pos1, pos2;
	int n;
	cout << "Enter Number of elements :";
	cin >> n;
	for (i = 0; i < n; ++i)
	{
		cout << "n Enter " << (i + 1) << "th Element :";
		cin >> a[i];
	}
	//Finding Largest
	for (i = 0; i < 10; ++i)
	{
		if (a[i] > largest)
		{
			largest = a[i];
			pos1 = i;
		}
	}
	//finding second largset
	for (i = 0; i < 10; ++i)
	{
		if (a[i] > second_largest)
		{
			if (a[i] == largest)
				continue;	//Ignoring largest in order to get second largest
			second_largest = a[i];
			pos2 = i;
		}
	}
	cout << "nn Largest Number :" << largest << " at position " << (pos1 + 1);
	cout << "nn Second Largest Number :" << second_largest << " at position " << (pos2 + 1);

	getch();
	return;
}

*Compiled using Visual Studio

OutputOutput of program to find the largest and second largest number present in an array

Muhammed Afsal Villan

Muhammed Afsal Villan is an experienced full-stack developer, specialized in desktop and mobile application development. He also regularly publishes quality tutorials on his YouTube channel named 'Genuine Coder'. He likes to contribute to open-source projects and is always enthusiastic about new technologies.

More From Author

UNIX Shell Programming – Complete Turtorial : Part 1

UNIX Shell Programming : grep,sed and awk

53 thoughts on “C++ program to find the largest and second largest number present in an array

  1. Pingback: post
  2. Pingback: bear archery
  3. Pingback: Casino Online
  4. Pingback: blote tieten
  5. Pingback: ltobet
  6. Pingback: ssr77
  7. Pingback: Mancave
  8. Pingback: echome
  9. Pingback: โคมไฟ
  10. Pingback: Silencer Shop
  11. Pingback: dultogel slot
  12. Pingback: สอนสัก
  13. Pingback: ufabet789
  14. Pingback: chatrooms
  15. Pingback: altogel
  16. Pingback: megac4
  17. Pingback: pgslot168
  18. Pingback: Go to instructions
  19. Pingback: stapelstein
  20. Pingback: HUAYHENG789

Leave a Reply