C++

Using C++, Find The Smallest Element In An Array

Find the least (minimum) element of an integer array after being provided the array. The user is first requested to enter the value for n (number of elements), and then they are asked to enter the elements of the array. The program then searches through the entered elements to identify the smallest one.

You should have a basic understanding of arrays, for loops, and functions in order to comprehend this program.

Program to identify the lowest element in an array of n elements, for instance

#include <iostream>
using namespace std;
int findSmallestElement(int arr[], int n){
   /* We are assigning the first array element to
    * the temp variable and then we are comparing
    * all the array elements with the temp inside
    * loop and if the element is smaller than temp
    * then the temp value is replaced by that. This
    * way we always have the smallest value in temp.
    * Finally we are returning temp.
    */
   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 = findSmallestElement(arr, n);
   cout<<"Smallest Element is: "<<smallest;
   return 0;
}

Output:

Enter the size of array: 5
Enter array elements: 11
9
18
88
101
Smallest Element is: 9

Explanation: The program prompts the user to input the array’s size before storing every element they enter in an array. After storing all of the entries in the array, the function is called with the arguments array and length.

The first element’s value was allocated to a variable in the function, and each element in the array was then compared to that variable. The loop runs until all of the items have been traversed, and if any element is small, its value is assigned to the variable. In this manner, the smallest member of the variable is present at the conclusion of the loop. That variable is being returned from the function.

Read the comments in the aforementioned program for more information.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button