You are given an integer array and you are asked to find the smallest (minimum) element of the array. This program asks the user to enter the value of n (number of elements) and then user is asked to enter the array elements. The program then finds the smallest element in the entered elements.
To understand this program you should have the basic knowledge of arrays, for loop and Functions.
Example: Program to find the smallest element in an array of n elements
#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:
Program asks the user to enter the size of array and then stores all the elements entered by user in an array. Once all the elements are stored in the array, the function is called by passing array and array length as argument.
In the function, we assigned the value of first element to a variable and then we compared that variable with every element of array. If any element is small then the value of that element is assigned to the variable and the loop continues until all the elements are traversed. This way we have the smallest element in the variable at the end of the loop. We are returning that variable from the function.
For more details read the comments given in the above program.
Leave a Reply