
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find 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
Advertisements