WAP to find smallest number of an array
Objective
Write a C++ program to find the smallest number in an array.
Algorithm / Approach
- Read 5 elements into an array.
- Assume the first element is the smallest:
min = a[0]. - Iterate through the array starting from index 1.
- If
min > a[i], updatemin = a[i]. - Print the minimum value.
main.cpp
#include<iostream>
using namespace std;
int main() {
int i, a[5] ;
cout<<"Enter 5 Elements : ";
for(i =0; i< 5; i++) {
cin>>a[i];
}
int min = a[0];
for(i =1; i 5; i++) {
if(min>a[i]) {
min = a[i];
}
}
cout<<"Min = "<< min<< endl;
return 0;
}
Expected Output
Enter 5 Elements : 12 34 11 36 342 Min = 11
Explanation of the Program
- This logic is identical to finding the maximum, just with the comparison operator flipped.
- Note on the provided code: the loop condition is written as
for(i =1; i 5; i++). It is missing the less-than operator (<). This will cause a compilation error. It should befor(i = 1; i < 5; i++).
Complexity
Time Complexity
O(n)
Space Complexity
O(n)
Common Mistakes
- Typo in the loop condition:
for(i =1; i 5; i++)is missing the<operator.