This is a C++ Program to Find the Largest and Smallest Elements in an Array.
Problem Description
The program takes an array and prints the largest and smallest element in the array.
Problem Solution
1. The program takes an array of elements.
2. Using a for loop, the largest and smallest element is found.
3. The result is printed.
4. Exit.
C++ Program/Source code
Here is the source code of C++ Program to Find the Largest and Smallest Elements in an Array. The program output is shown below.
#include
using namespace std;
int main ()
{
int arr[10], n, i, max, min;
cout << "Enter the size of the array : ";
cin >> n;
cout << "Enter the elements of the array : ";
for (i = 0; i < n; i++)
cin >> arr[i];
max = arr[0];
for (i = 0; i < n; i++)
{
if (max < arr[i])
max = arr[i];
}
min = arr[0];
for (i = 0; i < n; i++)
{
if (min > arr[i])
min = arr[i];
}
cout << "Largest element : " << max;
cout << "Smallest element : " << min;
return 0;
}
Runtime Test Cases
Case 1 :
Enter the size of the array : 5
Enter the elements of the array : 1 2 3 4 5
Largest element : 5
Smallest element : 1
Case 2 :
Enter the size of the array : 3
Enter the elements of the array : 36 136 0
Largest element : 136
Smallest element : 0
Case 3 :
Enter the size of the array : 10
Enter the elements of the array : 24 56 12 8 50 69 244 81 52 73
Largest element : 244
Smallest element : 8