max and second max in array code example
Example 1: how to find max in array
int[] a = new int[] { 20, 30, 50, 4, 71, 100};
int max = a[0];
for(int i = 1; i < a.length;i++)
{
if(a[i] > max)
{
max = a[i];
}
}
System.out.println("The Given Array Element is:");
for(int i = 0; i < a.length;i++)
{
System.out.println(a[i]);
}
System.out.println("From The Array Element Largest Number is:" + max);
Example 2: find maximum and second maximum number in array
#include <iostream>
int main()
{
std::cout << "Enter 5 numbers : ";
int arr[5];
for (int i = 0; i < 5; std::cin >> arr[i++]);
int max = arr[0], second = 0;
for (int i = 1; i < 5; i++)
if (arr[i] > max)
max = arr[i];
std::cout << "Maximum number : " << max << "\n";
bool found = false;
for (int i = 0; i < 5; i++)
{
if (arr[i] == max)
continue;
else if (arr[i] > second)
{
second = arr[i];
found = true;
}
}
if (found)
std::cout << "Second maximum numbers : " << second;
else
std::cout << "Second maximum number not found.";
}