Write a program that reads a list of integers, and outputs the two smallest integers in the list, in ascending order. The input begins with an integer indicating the number of integers that follow.
Ex: If the input is:
5 10 5 3 21 2
the output is:
2 and 3
You can assume that the list of integers will have at least 2 values.
To achieve the above, first read the integers into a vector.
Hint: Make sure to initialize the second smallest and smallest integers properly.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int>v;
int n;
cout << "Please, enter the number of integers: ";
cin >> n;
int tmp;
for (int i = 0; i < n; i++)
{
cin >> tmp;
v.push_back(tmp);
}
int smls1 = v[0];
int smls2 = v[0];
for (int i = 0; i < n; i++)
{
if(v[i]<smls1)
smls1=v[i];
}
for (int i = 0; i < n; i++)
{
if (v[i]<smls2&&v[i]!=smls1)
smls2 = v[i];
}
cout << "First 2 smallest elements are " << smls1 << " and " << smls2;
}
Comments
Leave a comment