Answer to Question #324839 in C++ for Program Training

Question #324839

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.



1
Expert's answer
2022-04-08T03:47:32-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS