This is a C++ Program to Find the Largest and Smallest Elements in an Array.
The program takes an array and prints the largest and smallest element in the array.
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.
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<iostream>
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;
}
1. The user is initially asked to enter the size of the array and it is stored in the variable ‘n’.
2. An array ‘arr’ of data type integer is declared with size 10.
3. Elements of the array are asked to enter and stored in ‘arr’ using a for loop.
4. The value at index 0 of arr is assigned to the variable ‘max’.
5. Using a for loop and initializing ‘i’ as 0, the largest element is found.
6. If max is less than arr[i], then value of arr[i] is assigned to max. i is incremented in every iteration.
7. The loop continues till ‘i’ is less than ‘n’.
8. Similarly, the smallest element is found.
9. The value at index 0 of arr is assigned to the variable ‘min’.
10. Using a for loop the smallest element is assigned to min.
11. The result is then printed.
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
Sanfoundry Global Education & Learning Series – C++ Programs.
To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.
- Check C++ Books
- Practice Programming MCQs
- Check Programming Books
- Apply for Computer Science Internship
- Apply for C++ Internship