Here is a C++ program to find minimum element of array using linear search. In this C++ program, we will find the smallest element of array by using linear search. Given an array of N elements, we have to find the smallest element of array.
For Example :Array : [8, 2, 10, -5, -2, 3, 0, 14] Smallest Element : -5
- First of all take number of elements as input from user. Let it be N.
- Then ask user to enter N numbers and store it in an array(lets call it inputArray).
- Initialize one variables minElement with first element of inputArray.
- Using a loop, traverse inputArray from index 0 to N -1 and compare each element with minElement. If current element is less than minElement, then update minElement with current element.
- After array traversal minElement will have the smallest element.
C++ Program to Find Smallest Element in Array
#include <iostream> using namespace std; int main(){ int input[100], count, i, min; cout << "Enter Number of Elements in Array\n"; cin >> count; cout << "Enter " << count << " numbers \n"; // Read array elements for(i = 0; i < count; i++){ cin >> input[i]; } min = input[0]; // search num in inputArray from index 0 to elementCount-1 for(i = 0; i < count; i++){ if(input[i] < min){ min = input[i]; } } cout << "Minimum Element\n" << min; return 0; }Output
Enter Number of Elements in Array 6 Enter 6 numbers 8 4 7 1 3 9 Minimum Element 1
In above C++ program we first take number of elements in array as input from user as store it in variable count. We then ask user enter "count" numbers and store it in an integer array "input". We initialize min with first element of input array and then traverse input array yo find smallest element as explained above. Finally, we print the value of smallest element in array using cout.
Recommended Posts