C++ Program to find smallest element in array

Simple C++ program to find smallest element in array: To find smallest element in array, first declare a variable smallest and initialize it to first element of array. Now compare it with all elements of array, if find any element less than smallest then update smallest to that element.
 
/* C++ program to find smallest element in array */
#include<iostream>
using namespace std;
int main()
{
 int arr[]={12,70,22,70,40,46,31};
 int n=sizeof(arr)/sizeof(arr[0]);
 int smallest=arr[0];
 
 for(int i=1;i<n;i++)
 {
  if(smallest>arr[i])
  {
   smallest=arr[i];
  }
 }
 cout<<"Smallest element in array: "<<smallest;
 return 0; 

/* End of the program */
 
 
Another C++ program to find smallest element using min function
 
/* C++ program to find smallest element in array */
#include<iostream>
using namespace std;
int min(int a,int b)
{
 if(a>b)
 return b;
 else
 return a;
}
int main()
{
 int arr[]={23,65,34,87,56,9,32,10};
 int n=sizeof(arr)/sizeof(arr[0]);
 int smallest=arr[0];
 
 for(int i=1;i<n;i++)
 {
  smallest=min(smallest,arr[i]);
 }
 cout<<"Smallest element in array: "<<smallest;
 return 0; 
}
/* End og the program */
 
C++ program to find smallest element in array using recursion
 
/* C++ program to find smallest element in array */
#include<iostream>
using namespace std;
int min(int a,int b)
{
 if(a>b)
 return b;
 else
 return a;
}
int FindSmallest(int arr[],int n)
{
 if(n==0)
 return arr[0];
 
 return min(FindSmallest(arr,n-1),arr[n]);
}
int main()
{
 int arr[]={300,65,34,87,56,90,320,100};
 int n=sizeof(arr)/sizeof(arr[0]);
 int smallest=FindSmallest(arr,n-1);
 
 cout<<"Smallest element in array: "<<smallest;
 return 0; 
}
/* End og the program */




Popular posts from this blog