Find Smallest and Largest Element in an Array
“Find Smallest and Largest Element in an Array” is an elementary problem of an Array data structure for beginners. Here, we are given an array of size ‘n’ and our task is to find the largest and smallest element of the array.
Example (Find smallest and Largest Element in an Array):
INPUT: Arr[5] = {4, 1, 3, 2, 5} OUTPUT: Largest Number = 5 Smallest Number = 1
The steps to find the largest and smallest elements of the array are as follows:
- Set largest = arr[0] and smallest = arr[0]
- Scan the array element from index 1 to (size-1). For each element,
Check if arr[i] > largest, then largest = arr[i]
and
Check if arr[i] < smallest, then smallest = arr[i]
3.Print the smallest and largest number.
C++ Program to find Smallest and Largest Element in an Array is as follows:
/* Program to find smallest and largest element in an array */
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
/* Scanning size of the array */
cout<<"Enter the number of array elements: ";
cin>>n;
/* Creating an Array */
int arr[n];
/* Scanning the array elements */
cout<<"\nEnter the array elements: ";
for(int i = 0; i < n; i++)
cin>>arr[i];
int smallest = arr[0];
int largest = arr[0];
/* Finding smallest and largest numbers */
for(int i = 1; i < n; i++)
{
if(arr[i] > largest)
largest = arr[i];
if(arr[i] < smallest)
smallest = arr[i];
}
/* Printing the result */
cout<<"\nThe smallest number in an array is "<<smallest;
cout<<"\nThe largest number in an array is "<<largest;
}
OUTPUT: Enter the number of array elements: 5 Enter the array elements: 2 5 3 1 4 The smallest number in an array is 1 The largest number in an array is 5 Time Complexity: O(n), where n is the size of the array
Related Posts:
- Program to count occurrences of a particular element in an array.
- Program to search an element in an Array (Linear Search).
- Program to Rotate Array Elements by ‘D’ positions.
- Program to find most frequent element in an array.
- Program to find pair in an array with given sum.
- Program to find first repeating element of an array.
- Program to merge two sorted arrays.
- Program to find missing number in an array.
- Program to sort if array is sorted.
- Program to print Alternate Elements of an Array.
- Program to Reverse a String.
- Program to Count Number of Characters in a String.
- Program to Count frequency of particular character of the String.
- Program to Count Number of Vowels and Number of Consonants in a String.
- Program to Check if String is alphabetic or numeric or alpha-numeric.
- Program to copy One Character Array to Another.
- Program to Concatenate Two Character Arrays.
- Program to Check whether given String is Palindrome or not.
- Program to convert lower-case alphabet to upper-case alphabet and vice-versa.
- Program to count total number of words in a string.