I have an array that will contains 5 random numbers between 0 to 99. I want to find the smallest and second smallest number of that array, I have the code below but it will not work if the first element is the smallest number. How can I fix this? Thank you for any help! :)
int numbers[5];
int main()
{
srand(time(NULL));
for(int i=0; i<5; i++){
numbers[i]=rand()%100;
cout<<numbers[i]<<" ";
}
cout<<endl;
int smallest = numbers[0], secondSmallest=numbers[0];
for(int i=0; i<5; i++){
if(numbers[i]<smallest){
secondSmallest=smallest;
smallest=numbers[i];
}
else if(numbers[i]<secondSmallest)
secondSmallest=numbers[i];
}
cout<<"Smallest number is : "<<smallest<<endl;
cout<<"Second smallest number is : "<<secondSmallest<<endl;
}
EDIT : this need to be done without sorting the array based on the requirements of the assignment.
Yet another way to get this done without using two loops. Takes care of duplicates.
int smallest = numbers[0],secondSmallest = numbers[0];
for(int i=0;i<5;i++){
if(numbers[i]>smallest){
if(numbers[i]<secondSmallest || smallest==secondSmallest){
secondSmallest = numbers[i];
}
}else{
if(secondSmallest>smallest && numbers[i]!=smallest){
secondSmallest=smallest;
}
smallest = numbers[i];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With