August 31, 2010
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
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 |
//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.