Find Smallest Number using Array in C++


This is a C++ program that finds the smallest element in an array of integers. The program first prompts the user to enter the size of the array, and then initializes an integer array of that size, called arr. It then prompts the user to enter the elements of the array one by one, which are stored in arr.

Next, the program calls a function called smallestelement, which takes in the array arr and its size n as parameters. Inside the function, the program initializes a variable temp to the first element of the array. It then loops through the remaining elements of the array using a for loop and compares each element with temp. If the element is smaller than temp, the program updates the value of temp to that element.

Finally, the function returns the value of temp, which is then outputted by the main function.

Source Code

#include <iostream>
using namespace std;
int smallestelement(int arr[],int n)
{
  int temp=arr[0];
  for(int i=0;i<n;i++)
  {
    if(temp>arr[i])
    {
       temp=arr[i];
    }
  }
  return temp;
}
int main()
{
  int n;
  cout<<"Enter the size of array: ";
  cin>>n;
  int arr[n-1];
  cout<<"Enter array elements: ";
  for(int i=0; i<n; i++)
  {
    cin>>arr[i];
  }
  int smallest = smallestelement(arr,n);
  cout<<"Smallest Element is: "<<smallest;
  return 0;
}
To download raw file Click Here

Output

Enter the size of array: 5 
Enter array elements: 11
12
13
14
15
Smallest Element is: 1

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples