# Find the smallest and second smallest elements in an array in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Suppose we have an array of n elements. We have to find the first, second smallest elements in the array. First smallest is the minimum of the array, second smallest is minimum but larger than the first smallest number.

Scan through each element, then check the element, and relate the condition for first, and second smallest elements conditions to solve this problem.

## Example

#include<iostream>
using namespace std;
int getTwoSmallest(int arr[], int n) {
int first = INT_MAX, sec = INT_MAX;
for (int i = 0; i < n; i++) {
if (arr[i] < first) {
sec = first;
first = arr[i];
}else if (arr[i] < sec) {
sec = arr[i];
}
}
cout << "First smallest = " << first << endl;
cout << "Second smallest = " << sec << endl;
}
int main() {
int array[] = {4, 9, 18, 32, 12};
int n = sizeof(array) / sizeof(array);
getTwoSmallest(array, n);
}

## Output

First smallest = 4
Second smallest = 9