
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find the smallest and second smallest elements in an array in C++
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[0]); getTwoSmallest(array, n); }
Output
First smallest = 4 Second smallest = 9
- Related Articles
- Maximum sum of smallest and second smallest in an array in C++
- Java program to find Largest, Smallest, Second Largest, Second Smallest in an array
- Maximum sum of smallest and second smallest in an array in C++ Program
- C program to find the second largest and smallest numbers in an array
- C# program to find Largest, Smallest, Second Largest, Second Smallest in a List
- Python program to find Largest, Smallest, Second Largest, and Second Smallest in a List?
- Find the lexicographically smallest sequence which can be formed by re-arranging elements of second array in C++
- Find frequency of smallest value in an array in C++
- C++ Program to Find Second Smallest of n Elements with Given Complexity Constraint
- Rearrange An Array In Order – Smallest, Largest, 2nd Smallest, 2nd Largest,. Using C++
- Find smallest and largest elements in singly linked list in C++
- C# Program to find the smallest element from an array
- C++ program to find Second Smallest Element in a Linked List
- Java program to find the smallest number in an array
- Find the first, second and third minimum elements in an array in C++

Advertisements