Q25. Write a code to find smallest element in an array
For Example :-
input : arr[]={ 5,5,8,3,5}
output : 3
So as we can see that the smallest element in arr[] = { 5,5,8,3,5} is 3 so the output is 3.
Algorithm for Smallest element in an array
START
Step 1 → Take an array Arr and define its values
Step 2 → Declare one variable (VAR) and assign 1st element of array to it
Step 3 → Loop for each value of Arr Repeat Step 4
Step 4 → If Arr[I] < VAR, Assign Arr[I] to VAR
Step 5 → After loop finishes, Display VAR which holds the smallest element of array
STOP
Code for Smallest element in an array
#include <stdio.h>
int main() {
int i, arr[5]={ 5,5,8,3,5};
int VAR = arr[0];
for (i = 1; i < 5; ++i) {
if (VAR > arr[i])
VAR = arr[i];
}
printf(“Smallest element in an Array is = %d”, VAR);
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int i, arr[5]={ 5,5,8,3,5};
int VAR = arr[0];
for(i = 1;i < 5; ++i)
{
if(VAR > arr[i])
VAR = arr[i];
}
cout << “Smallest element in an Array is = ” << VAR;
return 0;
}
public class LFC {
public static void main(String[] args) {
int[] numArray = { 5,5,8,3,5};
int smallest = numArray[0];
for (int num: numArray) {
if(smallest > num)
smallest = num;
}
System.out.format(“Smallest element in an Array is = %d”, smallest);
}
}
number = [5,5,8,3,5]
smallest_number = min(number);
print(“Smallest element in an Array is = “, smallest_number)
// Returns maximum in array
function getMin($arr)
{
$n = count($arr);
$min = $arr[0];
for ($i = 1; $i < $n; $i++)
if ($min > $arr[$i])
$min = $arr[$i];
return $min;
}
// Driver code
$arr = array(5,5,8,3,5);
echo “Smallest element in an Array : “;
echo(getMin($arr));
Output
Smallest element in an Array is =3
Recommended Programs
Program to find factorial of a number
Program to count number of digits in a number